1. 程式人生 > >recyclerView的介面回撥點選事件和多級列表展示

recyclerView的介面回撥點選事件和多級列表展示

  //activity中的方法
  recyclerView = (RecyclerView) findViewById(R.id.rv3);
    list = new ArrayList<>();
    for (int i=0; i<1000;i++){
        list.add("這是條目"+i);
    }

    recyclerView.setLayoutManager(new LinearLayoutManager(Main4Activity.this,LinearLayoutManager.VERTICAL,false));
    DividerItemDecoration dividerItemDecoration = new 
DividerItemDecoration(this, DividerItemDecoration.VERTICAL); recyclerView.addItemDecoration(dividerItemDecoration); San san=new San(Main4Activity.this,list); recyclerView.setAdapter(san); san.setitemclick(this); } @Override public void onitem(int position) { Toast.makeText(Main4Activity.this
,"長按了"+list.get(position),Toast.LENGTH_LONG).show(); } @Override public void onitemlong(int position) { Toast.makeText(Main4Activity.this,"點選了"+list.get(position),Toast.LENGTH_LONG).show(); }
//呼叫介面
public interface Huidiao {
    public void onitem(int position);
    public void onitemlong(int position);

}
//在介面卡中
Huidiao onItemClickListner;//實列化介面物件
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder=null;
        View view;
        switch (viewType){
            case 0:

                view= LayoutInflater.from(context).inflate(R.layout.son,parent,false);
                holder=new Rightholder(view);

                break;

            case 1:
                view= LayoutInflater.from(context).inflate(R.layout.son2,parent,false);
                holder=new Textholder(view);
                break;
        }

        return holder;
    }

    @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (getItemViewType(position)==0){
    ((Rightholder)holder).t1.setText(list.get(position));
    ((Rightholder)holder).t1.setOnClickListener(new View.OnClickListener() {
        @Override
public void onClick(View view) {
            onItemClickListner.onitemlong(position);
        }
    });


}else if (getItemViewType(position)==1){
    ((Textholder)holder).t2.setText(list.get(position));
    ((Textholder)holder).t2.setOnClickListener(new View.OnClickListener() {
        @Override
public void onClick(View view) {
            onItemClickListner.onitem(position);
        }
    });

}
    }

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

    @Override
public int getItemViewType(int position) {
        if (position%2==0){
            return 0;
        }
        return 1;
    }
    public void setitemclick(Huidiao onItemClickListner){
this.onItemClickListner=onItemClickListner;

    }