1.写一个接口
2.让一个类去用这个接口,并进行接口回调:
2.1 在类中声明该接口 并吃用该接口
3.让回调的activity 去实现该接口
adapter中的代码:
packagecom.cmcc.recycleviewtest;
importandroid.content.Context;
importandroid.support.v7.widget.RecyclerView;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.TextView;
importjava.util.List;
/**
* Created by PC on 2017/5/5.
*/
public classMyAdapterextendsRecyclerView.Adapter {
privateContextmContext;
privateListmdata;
OnItemlickListennerlistenner;//声明接口
//给接口设置set方法
public voidsetOnitemClickListenner(OnItemlickListenner listenner){
this.listenner=listenner;
}
publicMyAdapter(Context context , List data) {
this.mContext=context;
this.mdata=data;
}
@Override
publicMyAdapter.VieHolder onCreateViewHolder(ViewGroup parent,intviewType) {
VieHolder holder =newVieHolder(LayoutInflater.from(mContext).inflate(R.layout.item_view, parent,false));
returnholder;
}
@Override
public voidonBindViewHolder(MyAdapter.VieHolder holder,intposition) {
holder.tv.setText(mdata.get(position));
}
@Override
public intgetItemCount() {
returnmdata.size();
}
public classVieHolderextendsRecyclerView.ViewHolder {
TextViewtv;
publicVieHolder(View itemView) {
super(itemView);
tv= (TextView) itemView.findViewById(R.id.tv_item);
//用这个接口,并进行接口回调
itemView.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
if(listenner!=null){
listenner.onClick(view,getLayoutPosition(),mdata.get(getAdapterPosition()));
}
}
});
}
}
//.定义一个接口
interfaceOnItemlickListenner{
voidonClick(View view,intposition,String data);
}
}
MainActivty代码
packagecom.cmcc.recycleviewtest;
importandroid.os.Bundle;
importandroid.support.v7.app.AppCompatActivity;
importandroid.support.v7.widget.LinearLayoutManager;
importandroid.support.v7.widget.RecyclerView;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Toast;
importjava.util.ArrayList;
importjava.util.List;
public class MainActivity extends AppCompatActivity implements MyAdapter.OnItemlickListenner {
RecyclerView mRecyclerView;
Listdata;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView= (RecyclerView) findViewById(R.id.recycle_view);
initData();
mRecyclerView.setLayoutManager(newLinearLayoutManager(this));
MyAdapter myAdapter =newMyAdapter(this,data);
Log.i("MainActivity",data.size()+"");
mRecyclerView.setAdapter(myAdapter);
myAdapter.setOnitemClickListenner(this);
}
private voidinitData() {
data=newArrayList<>();
for(inti=0;i<40;i++){
data.add("第"+i+"数据");
}
}
@Override
public voidonClick(View view,intposition, String data) {
Toast.makeText(MainActivity.this,"点击了第:"+position,Toast.LENGTH_SHORT).show();
}
}