1. 程式人生 > >RecyView+條目點選(介面回撥)

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,MyAdapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener {
private Context context;
private List 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());
    }
}

}