【发布时间】:2014-11-20 21:44:39
【问题描述】:
我有以下情况:
我有一个Activity 承载一个ViewPager,我有4 个Fragments;
开头的ViewPager包含片段A,
当用户在ViewPager上滑动时片段B进入ViewPager,然后片段C和片段D..等等……
现在,一旦 FragmentPagerAdapter 被实例化,至少会创建 2 个片段。
这带来了两个问题:
- 每个
Fragment都需要进行网络调用,但我不想做不必要的(如果用户从不滑动到Fragment B,我不想为Fragment B进行网络调用 ); - 类似于 1.),我需要在 Fragment 执行网络调用时显示
ProgessDialog,但如果用户从未访问过 Fragment B,我不想显示来自 Fragment B 的对话框...
请问在这种情况下我应该使用什么样的模式?
活动
public class PagerActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
ViewPager pager=(ViewPager)findViewById(R.id.pager);
TabPageIndicator tabs=(TabPageIndicator)findViewById(R.id.titles);
pager.setAdapter(buildAdapter());
tabs.setViewPager(pager);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
FragmentPagerAdapter
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
@Override
public int getCount() {
return (4);
}
@Override
public Fragment getItem(int position) {
if (position == 1) {
if (dashbardFragment == null)
dashbardFragment = DashBoardFragment.newInstance(position);
return dashbardFragment;
}
if (position == 0) {
if (listOfParticipantFragment == null)
listOfParticipantFragment = ListOfParicipantsFragment
.newInstance(position);
return listOfParticipantFragment;
}
}
1 个片段
public class ListOfParicipantsFragment extends Fragment {
public static ListOfParicipantsFragment newInstance(int position) {
ListOfParicipantsFragment frag = new ListOfParicipantsFragment();
return (frag);
}
public static String getTitle(Context ctxt, int position) {
return myApplication.getContext().getResources().getString(R.string.list_of_participants_fragment_title);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.guest_list_fragment_layout,
container, false);
return (result);
}
【问题讨论】:
-
我不明白您在寻找什么问题。如果文档中已经有标准方式,不是吗?
-
使用RoboSpice等异步请求框架之一。片段可以发布请求、取消请求和重新收集请求,即使它们由于方向等变化而重新创建。
-
失败的糟糕设计你的用户将不得不等待屏幕更新,因为它可以在屏幕外完成。
-
@danny117 不,这不是一个糟糕的设计。这是一个非常普遍的问题。假设您有一个有 5 个选项卡的应用程序,并且在每个选项卡中都有一个 ListView,每行都有一个图像,例如 google play、appstore 或许多其他应用程序。你打算什么时候加载这些标签的数据? “它可以在屏幕外完成”你能告诉我吗,因为我刚刚创建了这样一个,我必须采用这种方法,在每个片段中对用户真正可见我必须下载相关的列表视图图像和数据。
-
我也认为这实际上是一个糟糕的设计,原因如下: 使用 ViewPager 时,预期行为是准备好下一个和上一个片段供使用。甚至设置了 UI 行为,因此用户可以查看下一个/上一个项目,并且他们希望数据在那里。我同意你的特殊情况可能需要这种不寻常的行为,但你不应该再次使用 ViewPager,因为你打破了它的预期模式。考虑改用 fm.replace(fragment)。
标签: android