【发布时间】:2020-10-30 14:30:10
【问题描述】:
在我的RecyclerView 适配器中,我想根据项目的位置设置项目的上边距。我只希望 在第一个 项目之后的项目具有上边距。在我的代码中,我以编程方式设置了 RecyclerView 项目的边距。
但是,当我尝试将项目添加到 RecyclerView 时,该项目不可见。我查看了here 和here,但我的代码仍然无法正常工作。我在RecyclerView 内以编程方式设置边距有什么不同吗?我尝试使用LinearLayout.LayoutParams 和RecyclerView.LayoutParams,但仍然没有。
任何帮助将不胜感激。
更新:
我正在使用以下代码将dp 转换为px
int top = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
R.dimen.element_row_margin_top,
r.getDisplayMetrics()
);
我传递的是 RAW 维度值,而不是调用:resources.getDimen()。
这是我的onBindViewHolder 代码:
if (position != 0) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 10, 0, 0);
holder.linearLayout.setLayoutParams(params);
}
这是我的rec_list_item(包含一个Image 和2 个TextInputlayouts):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
ViewHolder 代码:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LinearLayout item = (LinearLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.rec_list_item, parent, false);
MyViewHolder vh = new MyViewHolder(item);
return vh;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public LinearLayout linearLayout;
public MyViewHolder(LinearLayout item) {
super(contributorItem);
linearLayout = item;
}
}
【问题讨论】:
标签: java android android-layout android-recyclerview