我正在设置一个RecyclerView,其中包含多个ImageButton, 每个ImageButton都有一个OnClick动作(启动一个Activity) 我的问题是,OnClick操作在ImageButtons上不起作用,但是在每个ImageButton之间有一个小间距(如果我要单击第一个按钮,则必须单击第一个和第二个按钮之间的空间)
我尝试更改图像大小
RecyclerView适配器:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recycler_view, parent, false);
return new ViewHolder(view);
}
// binds the data to the ImageButton in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
int currentCategory = mData.get(position).getImage();
holder.categoriesButton.setImageResource(currentCategory);
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageButton categoriesButton;
ViewHolder(View itemView) {
super(itemView);
categoriesButton = itemView.findViewById(R.id.image_Button_Category_id);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public int getItem(int id) {
return mData.get(id).getImage();
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
RecyclerLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/image_Button_Category_id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
这是在我的MainActivity中:
private void setRecyclerViewOn(ArrayList<Category> list) {
RecyclerView recyclerView = findViewById(R.id.recyclerView_id);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecyclerViewAdapter(this, list);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
startActivity(createIntent(position));
}
预期结果:每个ImageButton上必须具有单击侦听器
答案 0 :(得分:0)
尝试在onBindView()上添加点击侦听器
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
int currentCategory = mData.get(position).getImage();
holder.categoriesButton.setImageResource(currentCategory);
holder.vategoriesButton.setOnClickListener(...)
}