RecyclerView空数据提示

ViewPager中使用RecyclerView绑定数据时经常会遇到没有数据时,需要显示“无数据”提示用户。下面是我的做法,先上图片效果

原理很简单,没有数据时显示图片和文字提示。

1、xml布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_Product"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/lay_fragment_ProdutEmpty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ImageView
            android:id="@+id/img_fragment_ProdutEmpty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="15dp"
            android:background="@color/systemNoColor"
            android:scaleType="fitXY"
            android:src="@drawable/loadfailed" />

        <TextView
            android:id="@+id/tv_fragment_ProdutEmpty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="15dp"
            android:text="没有发现任何商品。。。"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/aliRed"
            android:textSize="12pt" />
    </LinearLayout>
</LinearLayout>

2、RecyclerView绑定代码控制:

/**
 * 获取品类商品回调处理
 * Author:William(徐威)
 * Create Time:2018-08-24
 */
private void getProductCallBack(String strResJson) {
    try {
        recycler_Product = view.findViewById(R.id.recycler_Product);
        lay_fragment_ProdutEmpty=view.findViewById(R.id.lay_fragment_ProdutEmpty);
        GetSelfWeightProductInfoResponseDto response = JsonHelper.convetJsonToClass(strResJson, GetSelfWeightProductInfoResponseDto.class);
        if (response != null && response.getResults() != null && response.getResults().size() > 0) {
            recycler_Product.setVisibility(View.VISIBLE);
            lay_fragment_ProdutEmpty.setVisibility(View.GONE);
            ProductList = response.getResults();
            final List<SelfWeightProductInfoDto> productListCurr = ProductList;
            ProductRecyclerAdapter productRecyAdapter = new ProductRecyclerAdapter(productListCurr, mContext);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);

            productRecyAdapter.setItemClickListener(new ProductRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    SelfWeightProductInfoDto model = productListCurr.get(position);
                    Toast.makeText(mContext, String.format("你点击了:%s,商品重量:%s kg", model.ProductName, MainApplication.ProductWeight), Toast.LENGTH_SHORT).show();
                }
            });
            recycler_Product.setLayoutManager(gridLayoutManager);
            recycler_Product.setAdapter(productRecyAdapter);
        }
        else {
            recycler_Product.setVisibility(View.GONE);
            lay_fragment_ProdutEmpty.setVisibility(View.VISIBLE);
        }
    } catch (Exception ex) {
        Toast.makeText(mContext, String.format("获取品类商品回调处理出错!错误信息:%s。", ex.getMessage()), Toast.LENGTH_LONG).show();
    }
}

上面完整代码我也贴下:

package com.msh.mshselfweighing.modelinfo;

import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.msh.mshselfweighing.MainApplication;
import com.msh.mshselfweighing.R;
import com.msh.mshselfweighing.dto.Category.GetSelfWeightProductCategoryRequestDto;
import com.msh.mshselfweighing.dto.Category.GetSelfWeightProductCategoryResponseDto;
import com.msh.mshselfweighing.dto.Category.SelfWeightProductCategoryDto;
import com.msh.mshselfweighing.dto.Product.GetSelfWeightProductInfoRequestBody;
import com.msh.mshselfweighing.dto.Product.GetSelfWeightProductInfoRequestDto;
import com.msh.mshselfweighing.dto.Product.GetSelfWeightProductInfoResponseDto;
import com.msh.mshselfweighing.dto.Product.Product_PriceDto;
import com.msh.mshselfweighing.dto.Product.SelfWeightProductInfoDto;
import com.msh.mshselfweighing.modelinfo.adapter.ProductRecyclerAdapter;
import com.msh.mshselfweighing.utils.AppConfig;
import com.msh.mshselfweighing.utils.EnumCls;
import com.msh.mshselfweighing.utils.JsonHelper;
import com.msh.mshselfweighing.utils.OkHttpManager;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品品类Fragment
 * Author:William(徐威)
 * Create Time:2018-08-21
 */
public class CategoryFragment extends Fragment {
    public View view;
    private ViewGroup viewGroup;
    private Context mContext;
    private int categorySysNo = 0;
    private String categoryName;
    private int count = 0;
    private List<SelfWeightProductInfoDto> ProductList;
    private ImageView img_fragment_ProdutEmpty;
    private RecyclerView recycler_Product;
    private TextView tv_fragment_ProdutEmpty;
    private LinearLayout lay_fragment_ProdutEmpty;

    public static CategoryFragment newInstance(int mcategorySysNo, String mcategoryName) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("mcategorySysNo", mcategorySysNo);
        bundle.putString("mcategoryName", mcategoryName);
        fragment.setArguments(bundle);
        return fragment;
    }

    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: //获取品类商品信息回调
                    if (msg.obj != null) {
                        try {
                            getProductCallBack(msg.obj.toString());
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    } else {
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        categorySysNo = getArguments().getInt("mcategorySysNo");
        categoryName = getArguments().getString("mcategoryName");
        view = inflater.inflate(R.layout.category_fragment_view, container, false);
        this.viewGroup = container;
        mContext = getActivity();

        getProduct();

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        count++;
        //请求服务
        if (isVisibleToUser) {

        }
    }

    /**
     * 获取品类商品
     * Author:William(徐威)
     * Create Time:2018-08-24
     */
    private void getProduct() {
        try {
            final GetSelfWeightProductInfoRequestDto request = new GetSelfWeightProductInfoRequestDto();
            request.setSource(AppConfig.StoreServicesSource);
            request.setSecret(AppConfig.StoreServicesSecret);
            GetSelfWeightProductInfoRequestBody requestBody = new GetSelfWeightProductInfoRequestBody();
            requestBody.setStockSysNo(String.valueOf(MachineBaseInfo.getStockSysNo()));
            requestBody.setImageType(EnumCls.ImageType.ProductListImg.getCode());
            requestBody.setProductCategotySysNo(String.valueOf(categorySysNo));
            requestBody.setLoadImage(true);
            request.setBody(requestBody);
            try {
                OkHttpManager.sendPost(request, "GetSelfWeightProductInfo",
                        new OkHttpManager.ResultCallback() {
                            @Override
                            public void onCallBack(OkHttpManager.State state, String result) {
                                //Log.e("onCallBack",":------------result:"+result);
                                Message message = handler.obtainMessage();
                                message.what = 1;
                                message.obj = result;
                                handler.sendMessage(message);
                            }
                        });
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取品类商品回调处理
     * Author:William(徐威)
     * Create Time:2018-08-24
     */
    private void getProductCallBack(String strResJson) {
        try {
            recycler_Product = view.findViewById(R.id.recycler_Product);
            lay_fragment_ProdutEmpty=view.findViewById(R.id.lay_fragment_ProdutEmpty);
            GetSelfWeightProductInfoResponseDto response = JsonHelper.convetJsonToClass(strResJson, GetSelfWeightProductInfoResponseDto.class);
            if (response != null && response.getResults() != null && response.getResults().size() > 0) {
                recycler_Product.setVisibility(View.VISIBLE);
                lay_fragment_ProdutEmpty.setVisibility(View.GONE);
                ProductList = response.getResults();
                final List<SelfWeightProductInfoDto> productListCurr = ProductList;
                ProductRecyclerAdapter productRecyAdapter = new ProductRecyclerAdapter(productListCurr, mContext);
                GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);

                productRecyAdapter.setItemClickListener(new ProductRecyclerAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        SelfWeightProductInfoDto model = productListCurr.get(position);
                        Toast.makeText(mContext, String.format("你点击了:%s,商品重量:%s kg", model.ProductName, MainApplication.ProductWeight), Toast.LENGTH_SHORT).show();
                    }
                });
                recycler_Product.setLayoutManager(gridLayoutManager);
                recycler_Product.setAdapter(productRecyAdapter);
            }
            else {
                recycler_Product.setVisibility(View.GONE);
                lay_fragment_ProdutEmpty.setVisibility(View.VISIBLE);
            }
        } catch (Exception ex) {
            Toast.makeText(mContext, String.format("获取品类商品回调处理出错!错误信息:%s。", ex.getMessage()), Toast.LENGTH_LONG).show();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/xuwei_net/article/details/82150156