android - Recycler ItemDecoration - 未绘制分隔线,不确定原因
问题描述
我试图在我的垂直回收视图中显示一些分隔线。当我使用提供的默认分隔符时:
mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
mRecycler.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
mRecycler.setAdapter(adapter);
它工作得很好。但是,当我编写自己的自定义类时,什么都没有显示,我也不知道为什么。
public class PostDivider extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public PostDivider(Context context) {
mDivider = ContextCompat.getDrawable(context, R.drawable.divider_horizontal);
}
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
这是R.drawable.divider_horizontal
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="16dp" />
<solid android:color="@color/steelBlue" />
</shape>
添加我的自定义分隔线:
mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
mRecycler.addItemDecoration(new PostDivider(mContext));
mRecycler.setAdapter(adapter);
编辑:我换成了mContext
getActivity() 并且它没有返回 null。所以我很迷茫为什么它不起作用
Edit2:似乎是一个观众问题
我将整个视图简化为:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorWhite"
android:layout_margin="20dp">
<ImageView
android:id="@+id/vh_buisnesspost_buisness_preview"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/background_circle_preview_border"/>
<ImageView
android:id="@+id/vh_buisnesspost_post_image"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="@color/colorAccent"
android:layout_below="@id/vh_buisnesspost_buisness_preview"/>
</RelativeLayout>
这是我感到困惑的地方:为什么当您添加到父布局时它只显示分隔线?!!!!android:layout_margin="20dp"
android:layout_marginBottom="20dp"
不工作只是android:layout_margin="20dp"
为什么?!!!!!!
解决方案
推荐阅读
- python - Python pandas DataFrame:使用经度将本地 UTM 时间转换为 GMT
- python - 如何创建一个函数来过滤掉列中的指定条件?
- javascript - 按下按钮后如何激活动画
- html - 获取和设置文本
- tensorflow - `tensorflow_federated.learning.from_keras_model()` 不再包含 'dummy_batch' 关键字?
- java - 有没有办法获取在 Java 中发送和接收的当前千比特数?
- docker - s2i 构建源代码卷映射而不是 --copy 或者在 s2i 执行后如何访问构建输出目录?
- linux - 在 netstat 输出中区分 TCP 服务器和客户端
- typescript - 如何在打字稿中将有区别的联合与函数重载结合起来
- tensorflow - Tensorflow tf.layer.batch_normalization:如何在训练期间使用全局移动统计数据进行归一化?