我有一個ProductListActivity,其中包含viewpager和tablayout。我正在設置FragmentProductCategory的viewpager適配器。在FragmentCategoryAdapter構造函數中,傳遞上下文和CategoryList引用。 CategoryList是簡單的pojo類,它包含categoryId & categoryName。在FragmentCategoryAdapter構造函數中,使用for循環我創建了ProductList(另一個包含產品相關信息的pojo類)ArrayList()實例,並將其另存爲CategoryList類的另一個實例,並使用它的另一個構造函數。 現在來自FragmentCategoryAdapter的getItem(),我使用它的newInstance()方法創建TabFragment,並根據其位置傳遞ProductList實例的refrence。在TabFragment類中,它包含recyclerview,我打電話給asycntask從服務器獲取產品列表。我正確地獲取onPostExecute中的數據。然後使用ProductListNotifyListener onTaskCompleted()方法將它傳入片段,並在此設置recyclerview適配器。 但是,打開ProductListActivity第一個選項卡從不在其加載中顯示數據。第二個問題是在滑動片段標籤數據交換。 我沒有得到我在這裏做錯了。請幫幫我。還請告訴我,我是否以標準方式進行所有這些過程?還有其他的方式嗎? 我發佈我的文件代碼。Android碎片數據加載到回收站
這是ProductListActivity.java
類public class ProductListActivity extends AppCompatActivity{
private List<CategoryList> categoryLists;
private static Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
public static FragmentProductCategory categoryAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
context = ProductListActivity.this;
/* Get category list from SharedPreferences */
categoryLists = new AppSharedPreference(this).getCategoryLists();
/* Setting up toolbar */
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* Displaying home page back button enabled */
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setHomeAsUpIndicator(getResources().getDrawable(R.drawable.ic_back_arrow));
/* Drawable drawable = getResources().getDrawable(R.drawable.ic_back_arrow);
if(drawable!=null){
int color = Color.parseColor("#535353");
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}*/
TextView textView = (TextView)toolbar.findViewById(R.id.titleToolbar);
textView.setTextColor(Color.parseColor("#535353"));
}
/* Setting tabs and titles as per no of categries */
/* Getting UI element's reference */
viewPager = (ViewPager) findViewById(R.id.viewPagerProductList);
tabLayout = (TabLayout) findViewById(R.id.tlProductList);
/*Creating fragment adapter class for tabs and setting it in viewpager */
categoryAdapter = new FragmentProductCategory(getSupportFragmentManager(),categoryLists,this);
viewPager.setAdapter(categoryAdapter);
/*Setting up tab layout with view pager and other effects*/
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorPrimary));
tabLayout.setTabTextColors(R.color.colorPrimary, R.color.colorPrimary);
tabLayout.setBackgroundColor(getResources().getColor(R.color.colorWhite));
tabLayout.setSelectedTabIndicatorHeight(6);
tabLayout.setSmoothScrollingEnabled(true);
/* Fetching intent data send from home activity and as per data get setting that particular tab */
String categoryId = getIntent().getStringExtra("category-id");
if(categoryId!=null){
int pos=0;
/* Looping through categoryList and matching categoryId received from intent to categoryList
* and on the basis of that fetching position of that particular tab
* */
for (int i=0;i<categoryLists.size();i++){
if(categoryLists.get(i).getCategoryId().equals(categoryId)){
// Log.d("cat-id111", categoryLists.get(i).getCategoryId() + "\n pos=" + pos);
pos=i;
}
}
viewPager.setCurrentItem(pos);
}
/** Getting product list from server as per
* category-id from other pages has get or
* by default load data for first tab category id
**/
if(categoryId==null){
categoryId = categoryLists.get(0).getCategoryId();
}
}
}
這是ProductList.java簡單的POJO類來存儲產品列表信息。
public class ProductList {
public String getCategoryId() {
return categoryId;
}
public String getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
public String getProductDetails() {
return productDetails;
}
public String getProductPrice() {
return productPrice;
}
public String getProductBarcode() {
return productBarcode;
}
public String getStockQuantity() {
return stockQuantity;
}
public String getOfferName() {
return offerName;
}
public String getOfferPrice() {
return offerPrice;
}
public String getThumb() {
return thumb;
}
public String getBanner() {
return banner;
}
public String getProductSize() {
return productSize;
}
public void setProductSize(String productSize) {
this.productSize = productSize;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setProductDetails(String productDetails) {
this.productDetails = productDetails;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public void setProductBarcode(String productBarcode) {
this.productBarcode = productBarcode;
}
public void setStockQuantity(String stockQuantity) {
this.stockQuantity = stockQuantity;
}
public void setOfferName(String offerName) {
this.offerName = offerName;
}
public void setOfferPrice(String offerPrice) {
this.offerPrice = offerPrice;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public void setBanner(String banner) {
this.banner = banner;
}
public ArrayList<String> getBannerList() {
return bannerList;
}
public ArrayList<ProductContentList> getContentList() {
return contentList;
}
public String categoryId;
public String productId;
public String productName;
public String productDetails;
public String productPrice;
public String productBarcode;
public String productSize;
public String stockQuantity;
public String offerName;
public String offerPrice;
public String thumb;
public String banner;
private ArrayList<String> bannerList;
private ArrayList<ProductContentList> contentList;
public ProductList(HashMap<String,String> hashMap){
this.categoryId=hashMap.get("categoryId");
this.productId=hashMap.get("productId");
this.productName=hashMap.get("productName");
this.productDetails=hashMap.get("productDetails");
this.productPrice=hashMap.get("productPrice");
this.productBarcode=hashMap.get("productBarcode");
this.productSize=hashMap.get("productSize");
this.stockQuantity=hashMap.get("stockQuantity");
this.offerName=hashMap.get("offerName");
this.offerPrice=hashMap.get("offerPrice");
this.thumb=hashMap.get("productImageLink");
prepareBannersAndContents(hashMap.get("bannerImageLinks"),hashMap.get("contentDetails"));
}
private void prepareBannersAndContents(String bannerLinks,String contentDetails){
try {
JSONArray pBannerArr = new JSONArray(bannerLinks);
bannerList = new ArrayList<>();
for (int j=0;j<pBannerArr.length();j++){
bannerList.add(j,pBannerArr.getJSONObject(j).getString("imageLink"));
}
JSONArray pDetailsArr = new JSONArray(contentDetails);
contentList = new ArrayList<>();
for (int j=0;j<pDetailsArr.length();j++){
JSONObject object = pDetailsArr.getJSONObject(j);
contentList.add(new ProductContentList(object.getString("quantity"),object.getString("iconLink")));
}
}catch (JSONException | NullPointerException jse){
jse.printStackTrace();
}
}
}
這是FragmentProductCategory.java viewpager適配器。
public class FragmentProductCategory extends FragmentStatePagerAdapter{
private int PAGE_COUNT;
private List<CategoryList> catList;
public static List<CategoryList> dataList;
public FragmentProductCategory(FragmentManager fragmentManager1, List<CategoryList> catList, Context context1){
super(fragmentManager1);
this.catList=catList;
this.PAGE_COUNT = catList.size();
dataList = new ArrayList<>();
for(int i=0;i<catList.size();i++){
List<ProductList> pList = new ArrayList<>();
dataList.add(new CategoryList(catList.get(i).getCategoryId(), catList.get(i).getCategoryName(), pList));
Log.d("ProductListTest",""+i);
}
}
@Override
public Fragment getItem(int position){
Log.d("ProductListTest","getItem"+position);
return TabFragment.newInstance(position, dataList.get(position).getCategoryId(), dataList.get(position).getCategoryName());
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
return catList.get(position).getCategoryName();
}
public void applyFilters(int pos){
//tabFragment1.applyFilterSortSizeOperations(pos);
}
public static class TabFragment extends Fragment implements ProductListNotifyListener{
private ProgressBar progressBar;
private LinearLayout llNoData;
private TextView tvNoDataMsg;
private Button btnTryAgain;
private Context context;
private RecyclerView recyclerView;
private ProductListAdapter productAdapter;
// on scroll
private static int fromIndex = 0,loadLimit = 20;
private int pagePosition;
private String catId,catName;
private static TabFragment fragment;
public static TabFragment newInstance(int position,String catId,String catName) {
Bundle args = new Bundle();
args.putInt("position", position);
args.putString("id", catId);
args.putString("name", catName);
fragment = new TabFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagePosition = getArguments().getInt("position");
catId = getArguments().getString("id");
catName = getArguments().getString("name");
context = getContext();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_product_category,container,false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
recyclerView = (RecyclerView) view.findViewById(R.id.rvProductCategory);
llNoData = (LinearLayout)view.findViewById(R.id.llNoData);
tvNoDataMsg = (TextView)view.findViewById(R.id.tvNoDataMsg);
btnTryAgain = (Button) view.findViewById(R.id.btnTryAgain);
tvNoDataMsg.setTypeface(new SetFonts(context).setSourceSansProRegularFonts(), Typeface.ITALIC);
GridLayoutManager linearLayoutManager = new GridLayoutManager(getContext(),2);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(new ItemOffsetDecoration(getContext(), R.dimen.item_offset_inner));
//new SoapClient(context).getProductList(catId, fromIndex, loadLimit, productLists, listAdditionalArgs, recyclerView, llNoData, progressBar,fragment,productAdapter);
final ArrayList<String> listAdditionalArgs = new ArrayList<>();
listAdditionalArgs.add(ProductListActivity.appliedProductSize);
listAdditionalArgs.add(ProductListActivity.appliedSort);
listAdditionalArgs.add(ProductListActivity.appliedMaxPrice);
listAdditionalArgs.add(ProductListActivity.appliedMinPrice);
new SoapClient(context).getProductListTest(catId,pagePosition, fromIndex, loadLimit, listAdditionalArgs,fragment,recyclerView,llNoData,progressBar);
recyclerView.addOnScrollListener(new ProductListScrollListener(linearLayoutManager, "",context) {
@Override
public void onLoadMore(String current_page_id, int fromIndex) {
//loadMoreData(current_page_id, productLists, fromIndex);
}
});
btnTryAgain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
llNoData.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
// new SoapClient(context).getProductList(catId, fromIndex, loadLimit, productLists, listAdditionalArgs, recyclerView,llNoData,progressBar);
}
});
}
@Override
public void onResume() {
super.onResume();
ProductListActivity.resetCartViewText();
//FragmentProductCategory.productAdapter.notifyData();
}
@Override
public void onTaskStart(RecyclerView recyclerView1,LinearLayout llNoData1,ProgressBar progressBar1) {
llNoData1.setVisibility(View.GONE);
progressBar1.setVisibility(View.VISIBLE);
recyclerView1.setVisibility(View.GONE);
}
@Override
public void onTaskCompleted(int position, String response) {
Log.d("ProductListTest","onTaskCompleted"+position);
List<ProductList> pList = dataList.get(position).getProductLists();
try {
pList.clear();
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
HashMap<String,String> hashMap1 = new HashMap<>();
hashMap1.put("productId",jsonObject1.getString("productId"));
hashMap1.put("productName", jsonObject1.getString("productName"));
hashMap1.put("productDetails", jsonObject1.getString("productDetails"));
hashMap1.put("productPrice", jsonObject1.getString("productPrice"));
hashMap1.put("productBarcode", jsonObject1.getString("productBarcode"));
hashMap1.put("productSize", jsonObject1.getString("productSize"));
hashMap1.put("stockQuantity", jsonObject1.getString("stockQuantity"));
hashMap1.put("offerName", jsonObject1.getString("offerName"));
hashMap1.put("offerPrice", jsonObject1.getString("offerPrice"));
hashMap1.put("productImageLink", jsonObject1.getString("productImageLink"));
hashMap1.put("bannerImageLinks", jsonObject1.getString("bannerImageLinks"));
hashMap1.put("contentDetails", jsonObject1.getString("contentDetails"));
pList.add(new ProductList(hashMap1));
}
productAdapter = new ProductListAdapter(pList,context);
recyclerView.setAdapter(productAdapter);
productAdapter.notifyData();
dataList.get(position).setProductLists(pList);
}catch (JSONException jse){
jse.printStackTrace();
}
}
@Override
public void onException() {
llNoData.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
}
}
}
這是CategoryList.java,一個簡單的pojo類來存儲類別列表信息和ProductList實例引用。
public class CategoryList {
private String categoryId,categoryName;
private List<ProductList> productLists;
private ProductListAdapter productListAdapter;
public CategoryList(String categoryId,String categoryName){
this.categoryId=categoryId;
this.categoryName=categoryName;
}
public CategoryList(String categoryId,String categoryName,List<ProductList> productLists){
this.categoryId=categoryId;
this.categoryName=categoryName;
this.productLists=productLists;
}
public String getCategoryId() {
return categoryId;
}
public String getCategoryName() {
return categoryName;
}
public List<ProductList> getProductLists() {
return productLists;
}
public void setProductLists(List<ProductList> productLists) {
this.productLists = productLists;
}
}
這是其在TabFragment.java類實現ProductListNotifyListener.java接口
public interface ProductListNotifyListener {
public void onTaskStart(RecyclerView recyclerView,LinearLayout llNoData,ProgressBar progressBar);
public void onTaskCompleted(int position,String response);
public void onException();
}
這是ProductListAdapter.java其用於在recylerview顯示數據
public class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.MyViewHolder>{
public static List<ProductList> productLists;
private Context context;
private SetFonts setFonts;
private AppSharedPreference sharedPreference;
public AlertDialog alertDialogProductDetails;
public int productDetailsPosition;
public ProductListAdapter(){}
public ProductListAdapter(List<ProductList> productLists,Context context){
this.productLists=productLists;
this.context=context;
sharedPreference = new AppSharedPreference(context);
/* Getting reference of SetFont class */
setFonts = new SetFonts(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView tvProductName,tvProductPrice,tvPriceSymbol;
ImageView ivProductThumb,ivInformation,ivCart;
public MyViewHolder(View view){
super(view);
ivProductThumb = (ImageView) view.findViewById(R.id.ivProductThumb);
ivInformation = (ImageView)view.findViewById(R.id.ivInformation);
ivCart = (ImageView)view.findViewById(R.id.ivCart);
tvProductName = (TextView) view.findViewById(R.id.tvProductName);
tvProductPrice = (TextView) view.findViewById(R.id.tvProductPrice);
tvPriceSymbol = (TextView)view.findViewById(R.id.tvPriceSymbol);
/* Applying custom fonts */
tvProductName.setTypeface(setFonts.setSourceSansProSemiboldFonts());
tvProductPrice.setTypeface(setFonts.setSourceSansProRegularFonts());
}
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.adapter_product_list,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
try {
if(sharedPreference.isProductAddedInCart(productLists.get(position).getProductId())){
holder.ivCart.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_cart_added));
}else {
holder.ivCart.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_cart));
}
/* JSONArray jsonArray = new JSONArray(productLists.get(position).getThumb());
JSONObject jsonObject = jsonArray.getJSONObject(0);*/
String imageLink = productLists.get(position).getThumb();
Glide.with(context).load(imageLink).thumbnail(0.5f).animate(R.anim.fade_in).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.img_placeholder_1x1).into(holder.ivProductThumb);
holder.tvProductName.setText(productLists.get(position).getProductName());
holder.tvProductPrice.setText(productLists.get(position).getProductPrice());
}catch (ArrayIndexOutOfBoundsException | NullPointerException jse){
jse.printStackTrace();
}
}
@Override
public int getItemCount() {
if(productLists.size()>0){
return productLists.size();
}
return 0;
}
public void notifyData(){
notifyDataSetChanged();
}
}
請提供您的所有設計(.xml),以便我詳細闡述它。並且還提供AppSharedPreference,SetFonts,ProductContentList文件。 –
嗨帕特里克,我已經解決了我的問題。並張貼我的答案。不過謝謝你給我寶貴的時間閱讀我的文章。再次感謝你 –