1.寫(xiě)一個(gè)接口
2.讓一個(gè)類(lèi)去用這個(gè)接口猪钮,并進(jìn)行接口回調(diào):
? ? ?2.1 在類(lèi)中聲明該接口 并吃用該接口
3.讓回調(diào)的activity 去實(shí)現(xiàn)該接口
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;//聲明接口
//給接口設(shè)置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);
//用這個(gè)接口亿汞,并進(jìn)行接口回調(diào)
itemView.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
if(listenner!=null){
? ? ? ?listenner.onClick(view,getLayoutPosition(),mdata.get(getAdapterPosition()));
? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? });
? ?}
}
//.定義一個(gè)接口
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+"數(shù)據(jù)");
}
}
@Override
public voidonClick(View view,intposition, String data) {
Toast.makeText(MainActivity.this,"點(diǎn)擊了第:"+position,Toast.LENGTH_SHORT).show();
}
}