【问题标题】:Nested fragments: Detect click on outer fragment from within inner fragment嵌套片段:检测从内部片段内点击外部片段
【发布时间】:2015-06-05 08:07:42
【问题描述】:

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

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

【问题讨论】:

  • 请在您的问题中包含更多信息,例如布局 XML 或您尝试解决问题的任何方法。

标签: android android-layout android-fragments


【解决方案1】:

即兴发挥,我想说在Fragment1 中创建一个监听器interface,然后在Fragment2 中实现该接口,并在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
    }

}

【讨论】:

  • 我没有包含它,因为我最初假设您已经知道这部分,但您还需要将片段注册为可点击。我只在按钮上使用过 OnClickListener,它可以通过 xml 进行点击,但这里有一个例子:stackoverflow.com/a/14951225/1541763
  • 嘿,谢谢。我会尽快实现这一点。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 2021-12-03
  • 2017-07-13
  • 1970-01-01
相关资源
最近更新 更多