【发布时间】:2015-07-19 17:11:12
【问题描述】:
我在呈现自定义视图内部回收器视图小部件时遇到问题。传统上我们在 RecylerView.Adapter 中膨胀视图,就像
public RowLayoutViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_view, viewGroup, false);
RowLayoutViewHolder rowLayoutViewHolder = new RowLayoutViewHolder(view);
return rowLayoutViewHolder;
}
这很好用,我们可以将数据绑定到 onBindViewHolder(...) 方法中的视图。但是当我尝试创建 ViewGroup 的子类并像这样使用它时,我得到一个空白(“黑色”)屏幕。
public ImageGalleryAdapter.RowLayoutViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
SampleView view = new SampleView(context);
RowLayoutViewHolder rowLayoutViewHolder = new RowLayoutViewHolder(view);
return rowLayoutViewHolder;
}
这是我的 SampleView 类 -
public class SampleView extends ViewGroup {
public SampleView(Context context) {
super(context);
initView();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.layout(l, t, l + 600, t + 200);
}
}
private void initView() {
inflate(getContext(), R.layout.sample_view, this);
TextView textView = (TextView) findViewById(R.id.sampleTextView);
textView.setTextColor(Color.WHITE);
textView.setText("Hello from textview");
}
}
这是布局 -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/sampleTextView"
android:text="Sample TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
查看源代码似乎膨胀布局的行为与创建视图完全相同,只是膨胀过程基于 rootView 为子视图添加了合适的 LayoutParameter。我试过手动添加,但没有任何结果。
我们将不胜感激。
【问题讨论】:
-
你找到解决这个问题的方法了吗,我有类似的问题,因为我在我的回收站视图中使用视图持有者如何在其布局中自定义视图,当我向后滚动并快速滚动时回收站视图只是错过了一些绘制,并在屏幕上留下了回收站视图中的一些先前项目
-
我找到了解决方案。因为我错过了滚动时回收器视图需要重新填充所有内容的部分,所以我没有填充布局的每个部分,这非常重要,这就是为什么我从其他一些子视图中查看数据的原因。
标签: android android-custom-view android-recyclerview