Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在片段内分配接口_Android_Android Fragments - Fatal编程技术网

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(..)
in
Fragment
AnotherFragment abc = new AnotherFragment ();
mListener = abc;