Android 如何使用外部按钮控制片段(在Viewpager中)?
我不知道如何使用按钮修改片段中的数据Android 如何使用外部按钮控制片段(在Viewpager中)?,android,android-fragments,Android,Android Fragments,我不知道如何使用按钮修改片段中的数据 <Button android:id="@+id/bt" android:layout_width="match_parent" android:layout_height="wrap_content"/> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="fill_parent"
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/bt" >
<!-- Fragments -->
</android.support.v4.view.ViewPager>
您必须使用回调。只需编写一个接口,例如:
public interface ExampleCallback {
void onRequest(int param);
}
然后在片段中实现它:
public class ExampleFragment extends Fragment implements ExampleCallback {
//...
@Override
public void onRequest(int param) {
//doing an action using params
}
//...
}
在片段活动中创建一个字段:
ExampleFragmentCallback callback;
然后在寻呼机适配器中为片段分配一个引用,它可以如下所示:
class ExampleAdapter extends FragmentPagerAdapter{
//...
@Override
public Fragment getItem(int position) {
if(position == 1){
ExampleFragment toReturn = new ExampleFragment();
callback = (ExampleCallback) toReturn;
return toReturn;
}
//...
}
}
当然,适配器是片段活动中的一个内部类
最后,为按钮“bt”实现一个onClickListener,并在其中使用参数调用函数callback.onRequest()