我在LinearLayout
中創建了一個RecycleView
組件,其中還包含其他一些組件。問題是每當我點擊RecycleView
組件處的元素時,它應該在控制檯中創建一個TAG
,但它不會。我添加了onClickListiner
,但它根本沒有反應。RecycleView內部的按鈕在點擊時不起作用
下面是一段代碼,我如何在Activity
類和Adapter
內創建RecycleView
。
活動類:
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new MyAdapter(washLocations, this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
適配器:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<WashLocation> washLocations;
private LayoutInflater layoutInflater;
public MyAdapter(List<WashLocation> washLocations, Context context) {
layoutInflater = LayoutInflater.from(context);
this.washLocations = washLocations;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_recycleview, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context, contactView);
return viewHolder;
}
@Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
// Get the data model based on position
WashLocation w = washLocations.get(position);
String info = w.getWashName();
// Set item views based on your views and data model
TextView textView = holder.info;
textView.setText(info);
Integer fav = w.getFav();
Boolean favorite = fav == 1 ? true : false;
Button addToFav = holder.favorite;
addToFav.setText(favorite == true ? "Usuń z ulubionych" : "Dodaj do ulubionych");
}
@Override
public int getItemCount() {
return washLocations.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Context context;
public TextView info;
public Button favorite;
public ViewHolder(Context context, View itemView) {
super(itemView);
itemView.setOnClickListener(this);
this.context = context;
info = (TextView) itemView.findViewById(R.id.textView);
favorite = (Button) itemView.findViewById(R.id.addToFav);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition(); // gets item position
if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
// We can access the data within the views
Toast.makeText(context, info.getText(), Toast.LENGTH_SHORT).show();
Log.d("myTag", "This is my message");
}
}
}
}
是否有可能將兩個不同的'onClickListener'添加到'RecycleView'的一行中的不同按鈕? – bielas
是的,當然,我會編輯我的答案來做到這一點。 –
非常感謝! :)還有一件事 - 當我點擊按鈕時,是否有可以從偵聽器激活的列表中獲取對象? – bielas