如何在RecyclerView中设置相等的行高?

时间:2017-12-18 11:54:25

标签: android android-recyclerview

我有json数据文件,根据json数据显示不同大小的项目和行大小,但我想在RecyclerView中等于行大小。

如何实现我只发现GridLayoutManager只是{但不符合我的要求,任何帮助?

public class UserMsgAdpater extends RecyclerView.Adapter<UserMsgAdpater.MyViewHolder> {
public ArrayList<UserMessage> selected_usersList=new ArrayList<>();
private List<UserMessage> userList;
Context ctx;

TextView textview;
private SparseBooleanArray mSelectedItemsIds;

public UserMsgAdpater(Context context, List<UserMessage> data,ArrayList<UserMessage> selectedList) {
   this. userList = data;
   this. ctx = context;
   this.selected_usersList = selectedList;
    mSelectedItemsIds = new SparseBooleanArray();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView userName;
    public CardView cardView;

    public MyViewHolder(View view) {
        super(view);
        userName = (TextView) view.findViewById(R.id.user_temp);
    }
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.user_temp_list, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position)
{
    holder.userName.setText(userList.get(position).getMessage());

    holder.itemView
            .setBackgroundColor(mSelectedItemsIds.get(position) ?Color.GRAY
                    : Color.TRANSPARENT);

}
public void toggleSelection(int position) {
    selectView(position, !mSelectedItemsIds.get(position));
}

public void removeSelection() {
    mSelectedItemsIds = new SparseBooleanArray();
    notifyDataSetChanged();
}

//Put or delete selected position into SparseBooleanArray
public void selectView(int position, boolean value) {
    if (value)
        mSelectedItemsIds.put(position, value);
    else
        mSelectedItemsIds.delete(position);

    notifyDataSetChanged();
}

//Get total selected count
public int getSelectedCount() {
    return mSelectedItemsIds.size();
}

//Return all selected ids
public SparseBooleanArray getSelectedIds() {
    return mSelectedItemsIds;
}

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

public UserMessage get(int i) {
    return userList.get(i);
}}

在我的活动中,我正在使用此代码进行项目装饰,请查看。

mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
        mRecyclerView.addItemDecoration(new EqualSpacingItemDecoration(16,EqualSpacingItemDecoration.VERTICAL));

1 个答案:

答案 0 :(得分:0)

您可以在 ViewHolder构造函数中设置每个项目的高度:

for (i in errorSoon.indices) {
    print(errorSoon[i]+" ")
}

其中mHeight是所需项目高度的整数值。

对于您的代码,它看起来像这样:

TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, mHeight); 
itemView.setLayoutParams(params);