RecyclerView的简单使用在activity和fragment中

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38998213/article/details/90241361

主要就是activity和recycview,recycview和adapter;

主要就是fragment和recycview,recycview和adapter;

1.在build.gradle添加

RecyclerView的依赖,因为RecyclerView不是内置在android系统中的,请注意版本要一致
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:recyclerview-v7:27.1.1'
}

2.在布局中添加RecyclerView组件

 

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {

    private List<Fruit> mFruitList;

    static class ViewHolder extends RecyclerView.ViewHolder {
        View fruitView;
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(View view) {
            super(view);
            fruitView = view;
            fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            fruitName = (TextView) view.findViewById(R.id.fruit_name);
        }
    }

    public FruitAdapter(List<Fruit> fruitList) {
        mFruitList = fruitList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        holder.fruitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(), "you clicked view " + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        holder.fruitView.setOnLongClickListener(
                new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int position = holder.getAdapterPosition();
                        Fruit fruit = mFruitList.get(position);
                        Toast.makeText(v.getContext(), "你长时间按住了我 " + fruit.getName(), Toast.LENGTH_SHORT).show();
              //这里必须返回true,否则有可能引起点击事件混乱,因为优先响应的是长按事件,返回true可以在长按事件响应失败时把该点击事件消化掉,避免出错
                        return true;
                    }
                }
        );
        holder.fruitImage.setOnLongClickListener(
                new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int position = holder.getAdapterPosition();
                        Fruit fruit = mFruitList.get(position);
                        Toast.makeText(v.getContext(), "你长时间按住了我 " + fruit.getName(), Toast.LENGTH_SHORT).show();
                        return true;
                    }
                }
        );

        holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(), "you clicked image " + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    //这个方法主要用于适配渲染数据到View中  @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

    //BaseAdapter的getCount方法了,即总共有多少个条目
    @Override
    public int getItemCount() {
        return mFruitList.size();
    }

}

 

4.写一下Bean

 

public class Fruit {

    private String name;

    private int imageId;

    public Fruit(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }
}

 

5.在Activity里面写逻辑

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<Fruit>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);


        // 设置布局管理器
        //瀑布流
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);

        /*// 设置布局管理器
        //垂直分布和横向分布  LinearLayoutManager.HORIZONTAL  VERTICAL
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);*/
        recyclerView.setLayoutManager(layoutManager);


        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

    private void initFruits() {
        for (int i = 0; i < 5; i++) {
            Fruit apple = new Fruit(getRandomLengthName("Apple"), R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit(getRandomLengthName("Banana"), R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit(getRandomLengthName("Orange"), R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit(getRandomLengthName("Watermelon"), R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit(getRandomLengthName("Pear"), R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit(getRandomLengthName("Grape"), R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit(getRandomLengthName("Pineapple"), R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit(getRandomLengthName("Strawberry"), R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit(getRandomLengthName("Cherry"), R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit(getRandomLengthName("Mango"), R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }

    private String getRandomLengthName(String name) {
        Random random = new Random();
        //nextInt  产生一个大于0小于()内参数的随机数
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            builder.append(name);
        }
        return builder.toString();
    }

}

 

.在Fragment里面写逻辑

    <?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:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
    android:id="@+id/collect_recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
</android.support.v7.widget.RecyclerView>
</LinearLayout>

第二步:在fragment中定义使用

 

public class CollectFragment extends Fragment {
 private View view;//定义view用来设置fragment的layout
 public RecyclerView mCollectRecyclerView;//定义RecyclerView
 //定义以goodsentity实体类为对象的数据集合
 private ArrayList<GoodsEntity> goodsEntityList = new ArrayList<GoodsEntity>();
 //自定义recyclerveiw的适配器
 private CollectRecycleAdapter mCollectRecyclerAdapter;

 @Nullable
 @Override
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     //获取fragment的layout
     view = inflater.inflate(R.layout.collect_page, container, false);
     //对recycleview进行配置
     initRecyclerView();
     //模拟数据
     initData();
     return view;
 }

 /**
  * TODO 模拟数据
  */
 private void initData() {
     for (int i=0;i<10;i++){
         GoodsEntity goodsEntity=new GoodsEntity();
         goodsEntity.setGoodsName("模拟数据"+i);
         goodsEntity.setGoodsPrice("100"+i);
         goodsEntityList.add(goodsEntity);
     }
 }

 /**
  * TODO 对recycleview进行配置
  */

 private void initRecyclerView() {
     //获取RecyclerView
     mCollectRecyclerView=(RecyclerView)view.findViewById(R.id.collect_recyclerView);
     //创建adapter
     mCollectRecyclerAdapter = new CollectRecycleAdapter(getActivity(), goodsEntityList);
     //给RecyclerView设置adapter
     mCollectRecyclerView.setAdapter(mCollectRecyclerAdapter);
     //设置layoutManager,可以设置显示效果,是线性布局、grid布局,还是瀑布流布局
     //参数是:上下文、列表方向(横向还是纵向)、是否倒叙
     mCollectRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
     //设置item的分割线
     mCollectRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));
     //RecyclerView中没有item的监听事件,需要自己在适配器中写一个监听事件的接口。参数根据自定义
     mCollectRecyclerAdapter.setOnItemClickListener(new CollectRecycleAdapter.OnItemClickListener() {
         @Override
         public void OnItemClick(View view, GoodsEntity data) {
             //此处进行监听事件的业务处理
             Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();
         }
     });
 }

}
 

第三步设置RecyclerView的适配器

 

public class CollectRecycleAdapter extends RecyclerView.Adapter<CollectRecycleAdapter.myViewHodler> {
    private Context context;
    private ArrayList<GoodsEntity> goodsEntityList;

    //创建构造函数
    public CollectRecycleAdapter(Context context, ArrayList<GoodsEntity> goodsEntityList) {
        //将传递过来的数据,赋值给本地变量
        this.context = context;//上下文
        this.goodsEntityList = goodsEntityList;//实体类数据ArrayList
    }

    /**
     * 创建viewhodler,相当于listview中getview中的创建view和viewhodler
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public myViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {
        //创建自定义布局
        View itemView = View.inflate(context, R.layout.item_layout, null);
        return new myViewHodler(itemView);
    }

    /**
     * 绑定数据,数据与view绑定
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(myViewHodler holder, int position) {
        //根据点击位置绑定数据
        GoodsEntity data = goodsEntityList.get(position);
//        holder.mItemGoodsImg;
        holder.mItemGoodsName.setText(data.goodsName);//获取实体类中的name字段并设置
        holder.mItemGoodsPrice.setText(data.goodsPrice);//获取实体类中的price字段并设置

    }

    /**
     * 得到总条数
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return goodsEntityList.size();
    }

    //自定义viewhodler
    class myViewHodler extends RecyclerView.ViewHolder {
        private ImageView mItemGoodsImg;
        private TextView mItemGoodsName;
        private TextView mItemGoodsPrice;

        public myViewHodler(View itemView) {
            super(itemView);
            mItemGoodsImg = (ImageView) itemView.findViewById(R.id.item_goods_img);
            mItemGoodsName = (TextView) itemView.findViewById(R.id.item_goods_name);
            mItemGoodsPrice = (TextView) itemView.findViewById(R.id.item_goods_price);
            //点击事件放在adapter中使用,也可以写个接口在activity中调用
            //方法一:在adapter中设置点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //可以选择直接在本位置直接写业务处理
                    //Toast.makeText(context,"点击了xxx",Toast.LENGTH_SHORT).show();
                    //此处回传点击监听事件
                    if(onItemClickListener!=null){
                        onItemClickListener.OnItemClick(v, goodsEntityList.get(getLayoutPosition()));
                    }
                }
            });

        }
    }

    /**
     * 设置item的监听事件的接口
     */
    public interface OnItemClickListener {
        /**
         * 接口中的点击每一项的实现方法,参数自己定义
         *
         * @param view 点击的item的视图
         * @param data 点击的item的数据
         */
        public void OnItemClick(View view, GoodsEntity data);
    }

    //需要外部访问,所以需要设置set方法,方便调用
    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}

 

自定义实体类简单展示:

public class GoodsEntity implements Serializable {
    public String imgPath;//图片地址
    public String goodsName;//货物名称
    public String goodsPrice;//货物价格

    public GoodsEntity() {
    }

    public GoodsEntity(String imgPath, String goodsName, String goodsPrice) {
        this.imgPath = imgPath;
        this.goodsName = goodsName;
        this.goodsPrice = goodsPrice;
    }

    public String getImgPath() {
        return imgPath;
    }

    public void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getGoodsPrice() {
        return goodsPrice;
    }

    public void setGoodsPrice(String goodsPrice) {
        this.goodsPrice = goodsPrice;
    }

    @Override
    public String toString() {
        return "GoodsEntity{" +
                "imgPath='" + imgPath + '\'' +
                ", goodsName='" + goodsName + '\'' +
                ", goodsPrice='" + goodsPrice + '\'' +
                '}';
    }
}



 

展开阅读全文

没有更多推荐了,返回首页