我希望在我的Recyclerview结束时始终有一个按钮。基本上,用户可以在recyclerview中添加更多项目并删除它们,但按钮应该始终在最后。我很确定我不会将它添加到我的row.xml中,因为它只会使列表中的每个项目都有一个按钮。
答案 0 :(得分:0)
在我看来,最简单的方法是在您的recyclerview项目布局中设置按钮和内容容器,默认情况下按钮的可见性设置为已消失且内容的布局可见。显示最后一项时,只需设置布局的可见性并且按钮可见。
或者您可以使用2个不同的布局文件,例如此示例适配器:
public class YourAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int VIEW_TYPE_BUTTON = 0;
public static final int VIEW_TYPE_ITEM = 1;
private List<Object> items = Collections.emptyList();
public void setData(List<YourItem> itemList) {
items.clear();
items.addAll(itemList);
items.add("button");
notifyDataSetChanged();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView tvItemDescription; // just an example
public ItemViewHolder(View itemView) {
super(itemView);
tvItemDescription = itemView.findViewById(R.id.tv_description);
}
}
public class ButtonViewHolder extends RecyclerView.ViewHolder {
public Button button;
public ButtonViewHolder(View itemView) {
super(itemView);
button = itemView.findViewById(R.id.button);
button.addOnClickListener(/*add logic what should happen when the button is clicked*/);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
switch (viewType) {
case VIEW_TYPE_ITEM:
return new ItemViewHolder(inflater.inflate(R.layout.item, parent, false));
case VIEW_TYPE_BUTTON:
return new ButtonViewHolder(inflater.inflate(R.layout.item_button, parent, false));
default:
throw new IllegalArgumentException("no such view type defined");
}
return null;
}
@Override
public int getItemViewType(int position) {
Object item = items.get(position);
return (item instanceof YourItem) ? VIEW_TYPE_ITEM : VIEW_TYPE_BUTTON;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Object item = items.get(position);
if (item instanceof YourItem) {
YourItem yourItem = (YourItem) item;
YourAdapter.ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.tvItemDescription.setText(yourItem.description);
}
}
@Override
public int getItemCount() {
return items.size();
}
}
在这种情况下,通过在适配器数据集末尾添加一个不属于YourItem类型的项目,recyclerview将显示item_button.xml中定义的项目膨胀。 Haven实际上自己尝试过代码,但看看你是否可以运行它。