我的应用程序有两个嵌套片段,如下图所示:
如何从Fragment1
的实例中检测Fragment2
点击次数?
答案 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
}
}