1. 程式人生 > >Recyclerview 點選事件

Recyclerview 點選事件

// 介面卡程式碼

 
package com.example.a82.mouth; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /**  * Created by 82年的筆記本 on 2017/8/7.  */  public class MyAdapter extends RecyclerView.Adapter implements View.OnClickListener { Context context; List<String> list; OnItemClickListener onItemClickListener; public MyAdapter(Context context, List<String> list) { this.context = context; this.list = list; } @Override  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View inflate = View.inflate(context, R.layout.recycler, null); inflate.setOnClickListener(this); return new MyHolder(inflate); } @Override  public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { MyHolder myHolder = (MyHolder) holder; myHolder.textView.setText(list.get(position)); myHolder.itemView.setTag(position); } @Override  public void onClick(View v) { onItemClickListener.onItemClick(v, (Integer) v.getTag()); } interface OnItemClickListener { void onItemClick(View view, int position); } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override  public int getItemCount() { return list.size(); } class MyHolder extends RecyclerView.ViewHolder { private ImageView image; private TextView textView; public MyHolder(View itemView) { super(itemView); image = itemView.findViewById(R.id.image); textView = itemView.findViewById(R.id.text); } } } 

// MainActivity 程式碼

 
public class MainActivity extends AppCompatActivity { private RecyclerView recycler; @Override  protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); App.mainActivity = this; } private void initView() { recycler = (RecyclerView) findViewById(R.id.recycler); List<String> list = new ArrayList<>(); for (int i = 0; i < 50; i++) { list.add("" + i); } MyAdapter myAdapter = new MyAdapter(this, list); recycler.setLayoutManager(new LinearLayoutManager(this)); recycler.setAdapter(myAdapter); myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() { @Override  public void onItemClick(View view, int position) { Toast.makeText(MainActivity.this, "position:" + position, Toast.LENGTH_SHORT).show(); } }); }

}