我有一个有接口的片段,所以我可以将其他事件转发给其他片段。
public class MyFragment extends Fragment {
private MyListener mListener;
public interface MyListener {
public void doSomething(View o);
}
}
然后我在按钮
上使用它button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.doSomething(v);
}
});
但由于未分配,因此返回null。那么如何在当前片段上分配我的界面呢?
如果我想在另一个片段上实现这个怎么办?这可能吗?
public class AnotherFragment extends Fragment implements MyFragment.MyListener {
@Override
public void doSomething(View o){}
}
答案 0 :(得分:0)
试试这个
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener= (MyListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MyListener ");
}
}
答案 1 :(得分:0)
使用onAttach()方法。 来自谷歌的片段指南:
public static class MyFragment extends Fragment {
MyListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mListener = (MyListener) activity; // <-- For this to work, you need to implement your interface in the activity
}
...
}
也不要忘记在onDetach()中将引用归零
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
答案 2 :(得分:0)
因为您的mListener
为空 - >必须创造。
要使用界面:
AnotherFragment abc = new AnotherFragment ();
mListener = abc;
然后你可以致电:mListener.doSomething(v)