android中的动态标签,带有来自json的动态内容
Posted
技术标签:
【中文标题】android中的动态标签,带有来自json的动态内容【英文标题】:Dyanamic tabs in android with dynamic content from json 【发布时间】:2016-11-06 09:13:00 【问题描述】:我在 android 中创建动态选项卡,其中选项卡的数据是从 json 填充的
下面是json响应
"shop_details": [
"id": "36",
"shop_name": "All in One Mart",
"shop_no": "23223",
"shop_address": "Tinkune",
"phone": "9804966595",
"email": "arjundangal4@gmail.com",
"user_name": "arjun",
"address": "",
"tel": "",
"fax": "",
"facebook": "",
"twitter": "",
"googleplus": "",
"image": "",
"featured_image": ""
],
"category": [
"category_id": "35",
"category_name": "Skirt",
"product": [
"product_id": "49",
"product_name": "Skirt",
"category_id": "35",
"subcategory_id": "37",
"product_color": "blue",
"description": "Skirt for girls",
"price": "301",
"discount": "0",
"service_charge": "0",
"user_id": "36",
"image_name": "6baab8a5308b7e821f5b6387794979a4.jpeg",
"created_at": "2016-07-04 03:54:54"
]
,
"category_id": "36",
"category_name": "Men",
"product": [
"product_id": "48",
"product_name": "Glasses",
"category_id": "36",
"subcategory_id": "39",
"product_color": "red",
"description": "Glasses of Rayban",
"price": "594",
"discount": "23",
"service_charge": "22",
"user_id": "36",
"image_name": "fce01420a9021fdb159226b4bdc5b591.jpg",
"created_at": "2016-07-04 03:52:58"
]
,
"category_id": "37",
"category_name": "Bags",
"product": [
"product_id": "50",
"product_name": "Laptop bag",
"category_id": "37",
"subcategory_id": "41",
"product_color": "black",
"description": "Bag to carry laptop",
"price": "190",
"discount": "2",
"service_charge": "3",
"user_id": "36",
"image_name": "e836e090a54cd2b6b594fa0a3382bb38.jpg",
"created_at": "2016-07-04 04:14:08"
]
]
以下是获取动态添加标签的代码
private void getShopDetails()
coordinatorLayout.setVisibility(View.GONE);
new ProgressDialog(this);
ProgressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>()
@Override
public void onResponse(JSONObject response)
ProgressDialog.dismiss();
coordinatorLayout.setVisibility(View.VISIBLE);
try
JSONArray shopDetailsArray = response.getJSONArray("shop_details");
JSONObject shopDetailsObj = shopDetailsArray.getJSONObject(0);
shopName = shopDetailsObj.getString("shop_name");
phone = shopDetailsObj.getString("tel");
shopNum = shopDetailsObj.getString("shop_no");
shopAddress = shopDetailsObj.getString("shop_address");
shopImage = shopDetailsObj.getString("featured_image");
Glide.with(getApplicationContext()).load("http://allmartapp.com/appapi/uploads/" + shopImage).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(backdrop);
colLayout.setTitle(shopName);
address.setText("Address - Shop no -" + shopNum + ", " + shopAddress);
JSONArray tabsArray = response.getJSONArray("category");
categoryId = new int[tabsArray.length()];
for (int i = 0; i < tabsArray.length(); i++)
JSONObject tabsObj = tabsArray.getJSONObject(i);
tabLayout.addTab(tabLayout.newTab().setText(tabsObj.getString("category_name")));
categoryId[i] = tabsObj.getInt("category_id");
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
@Override
public void onTabSelected(TabLayout.Tab tab)
pager.setCurrentItem(tab.getPosition());
ShopDetailsTabsFragment.sgetid(categoryId[tab.getPosition()]);
Log.d("CATIID", categoryId[tab.getPosition()] + "");
@Override
public void onTabUnselected(TabLayout.Tab tab)
@Override
public void onTabReselected(TabLayout.Tab tab)
);
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
ProgressDialog.dismissWithError();
);
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
在 ontabselected() 中,我根据选项卡的位置分配了类别 ID,并调用了片段中的 sgetid() 函数
我的 pageradapter 只返回一个带有 recyclerview 的 Fragment。 以下是片段代码
public class ShopDetailsTabsFragment extends Fragment
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
public ShopDetailsTabsFragment()
// Required empty public constructor
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
return v;
@Override
public void setUserVisibleHint(boolean isVisibleToUser)
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null)
isViewShown = true;
getShopCat();
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
else
isViewShown = false;
public static void sgetid(int cat)
catid = cat;
private void getShopCat()
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>()
@Override
public void onResponse(JSONObject response)
Log.d("JSON", response.toString());
try
JSONArray categoryArray = response.getJSONArray("category");
for (int i = 0; i < categoryArray.length(); i++)
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid)
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++)
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("product_id");
CategoryItemsListModel shopListRvModels = new CategoryItemsListModel(id, image, name, price);
arrayList.add(shopListRvModels);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
);
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
我的问题是,标签显示出奇怪的行为。我知道获取类别列表的逻辑是正确的。但我认为片段的状态存在问题。当我切换选项卡时,有时会重复加载选项卡中的数据,甚至有时会加载两次数据。任何建议都会受到赞赏,因为我会在几天内面临这个问题。我想知道在选项卡中加载数据的简单方法。
【问题讨论】:
我也遇到了同样的问题,请问你是怎么解决的 【参考方案1】:如果有帮助,试试下面的代码:
public class ShopDetailsTabsFragment extends Fragment
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
public ShopDetailsTabsFragment()
// Required empty public constructor
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
return v;
@Override
public void setUserVisibleHint(boolean isVisibleToUser)
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null)
isViewShown = true;
getShopCat();
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
else
isViewShown = false;
public static void sgetid(int cat)
catid = cat;
private void getShopCat()
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>()
@Override
public void onResponse(JSONObject response)
Log.d("JSON", response.toString());
try
JSONArray categoryArray = response.getJSONArray("category");
if(arrayList!=null)
if(arrayList.size()>0)
arrayList.clear();
for (int i = 0; i < categoryArray.length(); i++)
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid)
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++)
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("product_id");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
shopListRvAdapters.notifyDataSetChanged();
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
);
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
【讨论】:
如何保存每个标签页的数据,这样每次显示标签页都不需要json请求?? 你可以保留一些像 isDataLoadedOnce=false 这样的标志,并在你第一次得到响应时让它为真,如果只有标志为假,则每次加载数据。但在这种情况下,注释掉 if(arrayList !=null) if(arrayList.size()>0) arrayList.clear();以上是关于android中的动态标签,带有来自json的动态内容的主要内容,如果未能解决你的问题,请参考以下文章
Android ViewPager + 带有动态 ListViews 的片段
如何将json对象的值设置为swift 3中tableView中动态呈现的视图中的标签?