嵌套片段:检测内部片段内的外部片段

时间:2015-06-01 19:43:31

标签: android android-layout android-fragments

我的应用程序有两个嵌套片段,如下图所示:

Fragments

如何从Fragment1的实例中检测Fragment2点击次数?

1 个答案:

答案 0 :(得分:2)

关闭袖口,我想在interface中创建一个监听器Fragment1,然后在Fragment2中实现该接口,并在Fragment1中的接口中调用相应的方法' onClick方法。

修改

这是一个非常准确的例子,我还没有对它进行过测试,但这是一般理论。当然,您需要添加逻辑并填写onCreate等必要的方法。

public class SampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize your activity here

        Fragment1 fragment1 = new Fragment1();
        Fragment2 fragment2 = new Fragment2();
        // Give fragment1 a reference to fragment2
        fragment1.registerListener(fragment2);
        // Do your fragment transactions here
    }
}

public class Fragment1 extends Fragment implements OnClickListener{

    // This is the interface. You can put as many abstract methods here as you want
    // with whatever parameters you want, but they all have to be overriden
    // in fragment2
    public interface FragmentClickListener {
        void onFragmentClick();
    }

    FragmentClickListener mListener;

    // This fragment needs to have a reference to the other fragment
    // This method can take any class that implements FragmentClickListener
    public void registerListener(FragmentClickListener mListener) {
        this.mListener = mListener;
    }

    @Override
    public void onClick(View view) {
        // You must check to make sure something is listening before you use the interface
        if (mListener != null) {
            //Let the interface know this fragment was clicked
            mListener.onFragmentClick();
        }
    }

}

public class Fragment2 extends Fragment implements FragmentClickListener {

    @Override
    public void onFragmentClick() {
        // Do whatever you want to do when fragment1 is clicked
    }

}