RecyView+条目点击(接口回调)

1,布局文件

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

2,MainActivity

public class MainActivity extends AppCompatActivity {

    private RecyclerView recy;
    private List<String> data;

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

        data = new ArrayList<>();
        for(int i=0;i<20;i++)
        {
            data.add("哈哈哈哈哈"+i);
        }


        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false);
        recy.setLayoutManager(linearLayoutManager);
        MyAdapter adapter=new MyAdapter(MainActivity.this, data);
        recy.setAdapter(adapter);
        adapter.setOnchickListenter(new MyAdapter.ItemChick() {
            @Override
            public void setOnItemClick(View view, int Position) {
                Toast.makeText(MainActivity.this,Position,Toast.LENGTH_LONG).show();
            }
        });
    }
}

3,Adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener {
    private Context context;
    private List<String> data;

    public MyAdapter(Context context, List<String> data) {
        this.context = context;
        this.data = data;
    }

    @NonNull
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view=LayoutInflater.from(context).inflate(R.layout.item,viewGroup,false);
        ViewHolder holder=new ViewHolder(view);

        view.setOnClickListener(this);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.ViewHolder viewHolder, int i) {
        viewHolder.tv.setText(data.get(i));
        viewHolder.itemView.setTag(i);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        private final TextView tv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = itemView.findViewById(R.id.tv);

        }
    }

    //点击事件的接口回调
    public interface ItemChick{
        void setOnItemClick(View view,int Position);
    }
    private ItemChick itemChick;
    public void setOnchickListenter(ItemChick itemChick)
    {
        this.itemChick=itemChick;
    }

    @Override
    public void onClick(View v) {

        if(itemChick!=null)
        {
            itemChick.setOnItemClick(v, (Integer) v.getTag());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值