我在呈现自定义 View 内部回收器 View 小部件时遇到问题。传统上,我们会在 RecylerView.Adapter 中膨胀 View ,例如
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;
}
这工作正常,我们可以将数据绑定(bind)到 onBindViewHolder(...) 方法中的 View 。但是当我尝试创建 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>
查看源代码似乎膨胀布局的行为与创建 View 完全相同,只是膨胀过程会基于 rootView 向 subview 添加合适的 LayoutParameter。我试过手动添加但没有任何结果。
我们将不胜感激。
最佳答案
这很简单。如果您看到通过膨胀来添加 View 的方式,您会意识到您正在将它添加到父级 (ViewGroup) 而不是附加它。在此过程中,将生成默认的 LayoutParams 并将其设置为您的 View 。 (检查 LayoutInflater 来源)
SampleView view = new SampleView(context);
view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
这是应该的。甚至以下似乎都有效。
viewGroup.add(view, new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
关于android - 在 RecyclerView 小部件中使用自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31503757/