alltolove 发表于 2017-9-30 06:17:45

android programing 3.6.3

FruitAdapter.java文件修改为package com.example.xinwei.myrecycleviewactivity;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
* Created by xinwei on 2017/9/28.
*/

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 view) {
                int position=holder.getAdapterPosition();
                Fruit fruit=mFruitList.get(position);
                Toast.makeText(view.getContext(), "you click view"+fruit.getName(), Toast.LENGTH_SHORT).show();
            }
      });
      holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position=holder.getAdapterPosition();
                Fruit fruit=mFruitList.get(position);
                Toast.makeText(view.getContext(), "you click image"+fruit.getName(), Toast.LENGTH_SHORT).show();
            }
      });
      return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
      Fruit fruit = mFruitList.get(position);
      holder.fruitImage.setImageResource(fruit.getImageId());
      holder.fruitName.setText(fruit.getName());
    }

    @Override
    public int getItemCount() {
      return mFruitList.size();
    }
}
这就是把每一项设置一个监听事件,非常的省事,效果图:
页: [1]
查看完整版本: android programing 3.6.3