我想用viewpager创建动态标签,但我不知道如何做到这一点。 我将从我的webservice 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创建选项卡表单类别(水果,饮料,动物),并且viewpager设置片段(片段只有listview,listview有图片和文本)
现在我的代码是静态的
我只设置了三个标签和三个片段来完成此操作。
屏幕:
现在我的代码:
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_width="match_parent"
android:layout_height="match_parent"
tools:context="edu.shu.foodtest.Food">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="40dp"
android:background="#EEEEEE"
android:theme="@style/ThemeOverlay.AppCompat.Light"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="wrap_content"
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_width="match_parent"
android:layout_height="match_parent"
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_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:orientation="vertical">
<ListView
android:id="@+id/listviewitem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:divider="@android:color/transparent"
android:dividerHeight="10dp"
android:scrollbars="none"></ListView>
</LinearLayout>
我想动态更改它,因为它将来会添加更多类别,如果我使用动态标签,它会自动从jsonstring添加标签
我是Android开发者的新手,我不知道的很多东西。我研究了很多数据,但我无法实现我想做的事。
希望有人可以告诉我如何做或给我一个样本来做这件事。
谢谢大家,我想对我糟糕的英语说抱歉,希望你能理解我的意思。
谢谢,谢谢!
答案 0 :(得分:0)
请参阅下面的代码。
我使用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();
}
}
}
<强> MainFragment 强>
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;
}
}