我的应用程序有两个嵌套的片段,如下图所示:
如何从Fragment1
实例中检测到Fragment2
的点击?
最佳答案
袖手旁观,我想说的是在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
}
}
关于android - 嵌套 fragment :检测内部 fragment 中外部 fragment 的点击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30581912/