我的应用程序主屏幕上有 10 个项目。每个都有不同的子类别(例如 item1 是 5,item8 是 3) 我的问题是关于解决此类问题的最佳实践。 我已经尝试过使用 fragment 页面适配器来加载页面(类别),但它似乎并没有解决我的问题。
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return x.newInstance();
case 1:
return y.newInstance();
case 2:
return z.newInstance();
default:
return null;
}
}
最佳答案
您能提供更多详细信息吗?您将选项卡称为项目吗? 每个类别是否由同一个类别代表?因为如果是这种情况,则向 newInstance 方法提供参数,您可以在其中指定所需的类别和项目数量,如下所示:
public class Frag_UserItems extends Fragment {
...
public static MyFragment newInstance (int itemsNumber, Category category){
// assuming category is an enum
Bundle bundle = new Bundle();
MyFragment fragment = new MyFragment();
bundle.setInt("num", itemsNumber);
bundle.setString("category", category.toString());
fragment.setArguments(args);
return fragment;
}
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_items, container, false);
//fetch the arguments and get the data from the reposotry
// and filter them how you want
Bundle args = getArguments();
int num = args.getInt("num");
String num = args.getString("category");
List<MyItem> items = ...
// bind view..
initview(rootView, items);
return rootView;
}
}
我认为您也可以将 fragment 实例存储在数组中,或者您可以将索引号传递给 newInstance 方法,然后您将根据索引创建 fragment ,这样它将把 getItem 减少为:
@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position);
}
public class Frag_UserItems extends Fragment {
...
public static MyFragment newInstance (int position){
// assuming category is an enum
Bundle bundle = new Bundle();
MyFragment fragment = new MyFragment();
bundle.setInt("num", position);
fragment.setArguments(args);
return fragment;
}
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_items, container, false);
//fetch the arguments and get the data from the reposotry
// and filter them how you want
Bundle args = getArguments();
int num = args.getInt("num");
List<MyItem> items = ...
// bind view..
initview(rootView, items);
return rootView;
}
}
这基本上遵循工厂方法模式。
希望这有帮助
关于java - 具有不同页码的 Viewpager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59251158/