我在安卓开发者网站上学习本教程http://developer.android.com/training/animation/screen-slide.html
我的处境是。。。
我有N个片段,代表我的viewpager中的每个页面,每个片段都不同,有自己的布局。这就是为什么我对每种类型的片段都有不同的类。
我想获得前几页中不同编辑文本的值,但在最后一页中,我想处理这些信息。
我不知道如何解决这个
您可以使用Intent或Bundle将信息从一个片段传递到其他片段。在第二个片段中处理该信息,然后再次使用Intent或Bundle将处理后的结果传递给第一个片段
示例:Intent和Bundle 的简单示例
正如@calvinfly所提到的,尝试实现一个接口。因为每个单独的片段都是唯一的,并且彼此不了解,所以它们之间唯一的链接是创建它们的适配器。因此,您可以在Fragment和它的适配器之间设置回调:
public class DummyFragment extends Fragment {
private OnEditTextSendListener mListener;
...
public interface OnSendTextListener { // this requires the adapter to implement sendMessage()
public void sendMessage(CharSequence msg);
}
public void setOnSendTextListener(OnSendTextListener listener) {
mListener = listener;
}
public View onCreateView( ... ) {
...
(EditText) editText = (EditText) rootView.findViewById(R.id.editText);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
mListener.sendMessage(v.getText());
}
}
}
}
注意:如果需要,指定侦听特定的actionId
(例如EditorInfo.IME_ACTION_SEND
.
然后在您的寻呼机适配器中:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
implements DummyFragment.OnSendTextListener {
private String mReceivedMessage;
// the required method to implement from the interface
public void sendMessage(CharSequence msg) {
mReceivedMessage = msg.toString();
notifyOnDataSetChanged(); // tell the adapter views need to be updated
}
}
从这里开始,当您对EditText执行操作时(一旦适配器调用setOnSendTextListener
并将其设置为自己,您将在下面看到),您的适配器现在会接收您的EditText输入。剩下的唯一一件事就是将此消息传递回相应的片段,可能在getItem
期间作为Bundle中的参数之一。
public Fragment getItem(int position) {
Fragment fragment;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new DummyFragment();
((DummyFragment) fragment).setOnSendTextListener(this);
break;
case 1:
// your other fragment
case 2:
// your other fragment that wants the message from 1st fragment
args.putString(DummyOtherFragment.ARG_DUMMYFRAGMENT_MSG, mReceivedMessage);
break;
default:
}
// other arguments here
fragment.setArguments(args);
return fragment;
}
希望这能有所帮助-请参阅Android开发人员指南创建活动回调)以了解更多信息。
附带说明:您可能会遇到这样的问题:适配器正确地接收到回调信息,但它传递数据的片段没有用数据重新加载(即使您正在调用notifyOnDataSetChanged()
。这本身就是另一个问题,我想引导您回答另一个关于ViewPager刷新片段以供进一步阅读的SO问题。
在您发布的教程中,我认为很明显,您必须实现getItem覆盖方法。在该网页中查找文本:
创建一个扩展FragmentStatePagerAdapter抽象的类类并实现getItem()
扩展Fragment或PagerAdapter的想法很常见。我为PagerAdapter做了这件事,我很高兴。