android - 嵌套 fragment : Detect click on outer fragment from within inner fragment

标签 android android-layout android-fragments

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

Fragments

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

最佳答案

即兴地说,我会说在 Fragment1 中创建一个监听器接口(interface),然后在 Fragment2 中实现该接口(interface)并调用适当的方法在 Fragment1onClick 方法的界面中。

编辑

这是一个非常简单的示例,我还没有测试过它,但这是一般理论。当然,您需要添加逻辑并填写必要的方法,例如 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
    }

}

关于android - 嵌套 fragment : Detect click on outer fragment from within inner fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30581912/

相关文章:

android - 按下按钮时查看密码编辑文本的值

java - 为什么我的 onStart() 函数在项目主要 Activity 开始时不起作用?

android - 为什么 View 行未显示在 item.xml 中

android - 如果我只请求读取权限,如何更改 Feed 对话框的受众。它默认为 "Only Me"

java - R 无法解析为 eclipse android 中的变量

android - 将 View 添加到窗口时如何获取 View 宽度和高度?

android - Android 的双向 ScrollView

android - 如何在 fragment 中使用 Retrofit 和 Loader 类

android - 两个 fragment 之间通过 Activity 进行的通信是否可以称为 android 中的观察者模式?

android - 如何修复我的 onclick 监听器,以便我不必单击两次即可在单击标题时触发事件?