2016-03-17 30 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