我的应用程序在主屏幕上有10个项目。它们都有不同的子类别(比如item1 his 5,item8 his 3),我的问题是实现这样一个问题的最佳实践。我已经尝试过使用片段页面适配器来加载页面(类别),但它似乎并没有解决我的问题。
@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;
}
}发布于 2019-12-09 15:07:07
你能提供更多细节吗?你指的是标签吗?每个类别都是由同一类预先设定的吗?因为如果是这样,那么向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;
}
}不认为还可以将片段实例存储在数组中,也可以将索引号传递给newInstance方法,然后在那里处理根据索引创建片段的问题,这样就可以将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;
}
}这基本上遵循了Factory方法模式。
我希望这能帮到你
发布于 2019-12-09 15:33:31
你应该给我们更多关于你要做什么的信息!但据我所知,你有一些项目,而且每个项目都有一些子项目。如果是我,我会用嵌套的RecyclerView!在这里,我找到了一篇很好的文章来帮助您:https://android.jlelse.eu/easily-adding-nested-recycler-view-in-android-a7e9f7f04047
我希望这就是你想要做的。
https://stackoverflow.com/questions/59251158
复制相似问题