如何使用 viewpager(android) 创建动态选项卡?
Posted
技术标签:
【中文标题】如何使用 viewpager(android) 创建动态选项卡?【英文标题】:How can I create dynamic tab with viewpager(android)? 【发布时间】:2018-01-02 17:48:29 【问题描述】:我想使用 viewpager 创建动态选项卡,但我不知道如何执行此操作。 我将从我的网络服务 API 中得到一个 jsonstring,如下所示:
"status":0,"data":["category":"fruit","pic":"URL","Content":"apple","category":"fruit","pic":"URL","Content":"banana","category":"fruit","pic":"URL","Content":"papaya","category":"drink","pic":"URL","Content":"milktea","category":"drink","pic":"URL","Content":"blacktea","category":"drink","pic":"URL","Content":"greentea","category":"animal","pic":"URL","Content":"dog","category":"animal","pic":"URL","Content":"cat","category":"animal","pic":"URL","Content":"lion"]
我想用viewpager创建tabs form category(fruit,drink,animal),viewpager设置fragment(fragment只有listview,listview有图片和文字)
现在我的代码是静态的
我只是设置了三个选项卡和三个片段来执行此操作。
屏幕:
enter image description here
现在我的代码:
Food.java
public class Food extends AppCompatActivity
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
private void setupViewPager(ViewPager viewPager)
FoodViewPagerAdapter adapter = new FoodViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment_Food_one(), "FRUIT");
adapter.addFragment(new Fragment_Food_two(), "DRINK");
adapter.addFragment(new Fragment_Food_three(), "ANIMAL");
viewPager.setAdapter(adapter);
activity_food.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
tools:context="edu.shu.foodtest.Food">
<android.support.design.widget.AppBarLayout
android:layout_
android:layout_
android:theme="@style/ThemeOverlay.AppCompat.Light">
<android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_
android:layout_
android:background="#EEEEEE"
android:theme="@style/ThemeOverlay.AppCompat.Light"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/toolbar_title"
android:layout_
android:layout_
android:layout_gravity="center"
android:singleLine="true"
android:text="test"
android:textColor="@color/red"
android:textSize="18sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_
android:layout_
app:tabMode="fixed"
app:tabGravity="fill"
android:background="#FFFFFF"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_
android:layout_
android:background="#EEEEEE"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
FoodViewPagerAdapter.java:
public class FoodViewPagerAdapter extends FragmentPagerAdapter
private final List<android.support.v4.app.Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public FoodViewPagerAdapter(FragmentManager manager)
super(manager);
@Override
public android.support.v4.app.Fragment getItem(int position)
return mFragmentList.get(position);
@Override
public int getCount()
return mFragmentList.size();
public void addFragment(android.support.v4.app.Fragment fragment, String title)
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
@Override
public CharSequence getPageTitle(int position)
return mFragmentTitleList.get(position);
Fragment_Food_one.java:
public class Fragment_Food_one extends Fragment
View view;
ListView mListView;
TextView BrandID;
String brandid;
ArrayList<Foodlistclass> arraylist = new ArrayList<Foodlistclass>();
private String result;
JSONObject response_object;
Context context;
String jsonstring="\"status\":0,\"data\":[\"category\":\"fruit\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"apple\",\"category\":\"fruit\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"banana\",\"category\":\"fruit\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"papaya\",\"category\":\"drink\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"milktea\",\"category\":\"drink\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"blacktea\",\"category\":\"drink\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"greentea\",\"category\":\"animal\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"dog\",\"category\":\"animal\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"cat\",\"category\":\"animal\",\"pic\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"Content\":\"lion\"]";
public Fragment_Food_one()
// Required empty public constructor
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_food_one, container, false);
context = getActivity().getApplicationContext();
mListView = (ListView) view.findViewById(R.id.listviewitem);
try
setlistview();
catch (JSONException e)
e.printStackTrace();
return view;
public void setlistview() throws JSONException
jsonstring = jsonstring.replace("\\", "");
response_object = new JSONObject(jsonstring.substring(jsonstring.indexOf(""), jsonstring.lastIndexOf("") + 1));
String status = response_object.getString("status");
if (status.equals("0"))
JSONArray responseData = response_object.optJSONArray("data");
for (int i = 0; i < responseData.length(); i++)
Map<String, Object> item = new HashMap<String, Object>();
JSONObject jsonChildNode = responseData.getJSONObject(i);
String category = jsonChildNode.optString("category");
System.out.println(category);
String Content = jsonChildNode.optString("Content");
System.out.println(Content);
String pic = jsonChildNode.optString("pic");
System.out.println(pic);
if (category.equals("fruit"))
arraylist.add(new Foodlistclass(
pic, Content, "a", "aW"
));
FoodlistAdapter adapter = new FoodlistAdapter(context, R.layout.food_listitem, arraylist);
mListView.setAdapter(adapter);
fragment_food_one.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_>
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_
android:layout_
android:background="@android:color/transparent"
android:orientation="vertical">
<ListView
android:id="@+id/listviewitem"
android:layout_
android:layout_
android:background="@android:color/transparent"
android:divider="@android:color/transparent"
android:dividerHeight="10dp"
android:scrollbars="none"></ListView>
</LinearLayout>
我想将其更改为动态,因为它会在将来添加更多类别,如果我使用动态选项卡,它将自动从 jsonstring 添加选项卡
我是android开发者的新人,很多东西我不知道。我研究了很多数据,但我无法实现我想做的事情。
希望有人能告诉我怎么做或给我一个样本来做这个。
谢谢大家,我想对我糟糕的英语说声抱歉,希望你能理解我上面的意思。
谢谢你!!!
【问题讨论】:
【参考方案1】:请看下面的代码。
我使用 Gson 将 Java 对象转换为它们的 JSON 表示,并将 JSON 字符串转换为等效的 Java 对象。
compile 'com.google.code.gson:gson:2.8.1'
物品
public class Item
private String category;
private String picture;
private String content;
public Item(JSONObject jsonObject) throws JSONException
category = jsonObject.getString("category");
picture = jsonObject.getString("picture");
content = jsonObject.getString("content");
public String getCategory()
return category;
public String getPicture()
return picture;
public String getContent()
return content;
MainActivity
public class MainActivity extends AppCompatActivity
private Map<String, List<Item>> list = new ArrayMap<>();
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Test");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
CategoriesPagerAdapter categoriesPagerAdapter = new CategoriesPagerAdapter(getSupportFragmentManager(), list);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(categoriesPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
private void loadData()
try
String jsonstring = "\"status\":0,\"data\":[\"category\":\"fruit\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"apple\",\"category\":\"fruit\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"banana\",\"category\":\"fruit\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"papaya\",\"category\":\"drink\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"milktea\",\"category\":\"drink\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"blacktea\",\"category\":\"drink\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"greentea\",\"category\":\"animal\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"dog\",\"category\":\"animal\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"cat\",\"category\":\"animal\",\"picture\":\"http://XXX.XXX.XXX.XXX/XXX.jpg\",\"content\":\"lion\"]";
String data = new JSONObject(jsonstring).get("data").toString();
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++)
JSONObject jsonObject = jsonArray.getJSONObject(i);
Item item = new Item(jsonObject);
String category = item.getCategory();
List<Item> itemList;
if (list.containsKey(category))
itemList = list.get(category);
list.remove(category);
else
itemList = new ArrayList<>();
itemList.add(item);
list.put(category, itemList);
catch (JSONException e)
e.printStackTrace();
主片段
public class MainFragment extends Fragment
public static final String KEY_ITEM_LIST = "key-item-list";
private List<Item> itemList = new ArrayList<>();
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if (getArguments() != null)
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Item>>()
.getType();
String itemsJson = getArguments().getString(KEY_ITEM_LIST);
itemList = gson.fromJson(itemsJson, type);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_main, container, false);
String test = "";
for (Item item : itemList)
test += "" + item.getContent();
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(test);
return view;
CategoriesPagerAdapter
public class CategoriesPagerAdapter extends FragmentPagerAdapter
private List<String> categories = new ArrayList<>();
private Map<String, List<Item>> list = new ArrayMap<>();
private SparseArray<MainFragment> mRegisteredFragments = new SparseArray<>();
public CategoriesPagerAdapter(FragmentManager manager, Map<String, List<Item>> list)
super(manager);
this.list = list;
for (String category : list.keySet())
categories.add(category);
@Override
public Fragment getItem(int position)
return newInstance(list.get(categories.get(position)));
@Override
public Object instantiateItem(ViewGroup container, int position)
MainFragment mainFragment = (MainFragment) super.instantiateItem(container, position);
mRegisteredFragments.put(position, mainFragment);
return mainFragment;
@Override
public void destroyItem(ViewGroup container, int position, Object object)
mRegisteredFragments.remove(position);
super.destroyItem(container, position, object);
@Override
public int getCount()
return categories.size();
@Override
public CharSequence getPageTitle(int position)
return categories.get(position);
private MainFragment newInstance(List<Item> items)
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Item>>() .getType();
MainFragment mainFragment = new MainFragment();
Bundle args = new Bundle();
args.putString(MainFragment.KEY_ITEM_LIST, gson.toJson(items, type));
mainFragment.setArguments(args);
return mainFragment;
【讨论】:
以上是关于如何使用 viewpager(android) 创建动态选项卡?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 viewpager(android) 创建动态选项卡?
如何在Android中使用viewPagerindicator和ViewPager?
Android studio:如何使用 ViewPager 添加标签
Android viewpager......如何获取视图?