2016-03-17 35 views
3

onAttach功能蝕示出了錯誤,說明我在onAttach獲得有關此奇怪的錯誤(上下文)

在類型片段的方法onAttach(活動)不是參數(上下文)

適用

雖然它顯然是如果你正在使用API​​通過

import android.content.Context; 

public class MyListFragment extends Fragment{ 
    private OnItemSelectedListener listener; 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_rsslist_overview, 
      container, false); 
     Button button = (Button) view.findViewById(R.id.button1); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
      updateDetail("fake"); 
      } 
     }); 
     return view; 
     } 

     public interface OnItemSelectedListener { 
     public void onRssItemSelected(String link); 
     } 

     @Override 
     public void onAttach(Context context) { 
     super.onAttach(context); 
     if (context instanceof OnItemSelectedListener) { 
      listener = (OnItemSelectedListener) context; 
     } else { 
      throw new ClassCastException(context.toString() 
       + " must implemenet MyListFragment.OnItemSelectedListener"); 
     } 
     } 

     @Override 
     public void onDetach() { 
     super.onDetach(); 
     listener = null; 
     } 

     // may also be triggered from the Activity 
     public void updateDetail(String uri) { 
     // create a string just for testing 
     String newTime = String.valueOf(System.currentTimeMillis()); 

     // inform the Activity about the change based 
     // interface defintion 
     listener.onRssItemSelected(newTime); 
     } 
} 
+0

發佈您的logCat –

+0

您正在使用的API級別? –

+0

@UsamaZafar targetSdk版本是15 – shruti

回答

1

我有同樣的問題可以嘗試通過活動在onAtach方法是這樣的:

@Override 
     public void onAttach(Activity activity) { 
     super.onAttach(context); 
     if (context instanceof OnItemSelectedListener) { 
      listener = (OnItemSelectedListener) activity; 
     } else { 
      throw new ClassCastException(context.toString() 
       + " must implemenet MyListFragment.OnItemSelectedListener"); 
     } 
     } 

,並告訴我,如果它工作或沒有。 希望能幫到你!

+0

謝謝!這對我工作 – shruti

+0

如果我的口水是幫助,你可以接受它,如果你想當然:) –

+0

接受你的answer.thanks再次幫助 – shruti

2

上下文類型變量23則

public void onAttach(Context context) { 

應該

public void onAttach(Activity context) { 

official docs

注:

onAttach(Context context)在API 23中添加見this

+0

謝謝,正是問題 – shruti

+0

@shruti如果它的工作,然後請不要忘記接受答案,然後請。 – Rohit5k2

+0

接受您的答案。再次感謝您的幫助 – shruti