Android 在片段内分配接口
我有这个片段,它有一个接口,所以我可以将其他事件中继到其他片段Android 在片段内分配接口,android,android-fragments,Android,Android Fragments,我有这个片段,它有一个接口,所以我可以将其他事件中继到其他片段 public class MyFragment extends Fragment { private MyListener mListener; public interface MyListener { public void doSomething(View o); } } 然后我在按钮上用这个 button.setOnClickListener(new View.OnClickLis
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){}
}
试试这个
@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 ");
}
}
为此使用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
}
...
}
因为您的
mListener
为空->必须创建。
要使用界面,请执行以下操作:
AnotherFragment abc = new AnotherFragment ();
mListener = abc;
然后您可以调用:mListener.doSomething(v)
mListener=(MyListener)活动代码>在onAttach(..)
inFragment
AnotherFragment abc = new AnotherFragment ();
mListener = abc;