use*_*373 6 android android-custom-view android-recyclerview
我在渲染自定义视图内部回收器视图小部件时遇到问题。传统上,我们在 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;
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,我们可以将数据绑定到 onBindViewHolder(...) 方法内的视图。但是当我尝试创建 ViewGroup 的子类并像这样使用它时,我得到一个空白(“黑色”)屏幕。
public ImageGalleryAdapter.RowLayoutViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
SampleView view = new SampleView(context);
RowLayoutViewHolder rowLayoutViewHolder = new RowLayoutViewHolder(view);
return rowLayoutViewHolder;
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是布局 -
<?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>
Run Code Online (Sandbox Code Playgroud)
查看源代码,膨胀布局的行为似乎与创建视图完全相同,只不过膨胀过程会根据 rootView 向子视图添加合适的 LayoutParameter。我尝试过手动添加,但没有任何结果。
任何帮助将不胜感激。
这很简单。如果您看到通过膨胀添加视图的方式,您会意识到您是将其添加到父级 (ViewGroup),但没有附加它。在此过程中,将生成默认的 LayoutParams 并将其设置为您的视图。(检查 LayoutInflater 源)
SampleView view = new SampleView(context);
view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)
事情应该是这样的。即使以下内容似乎也有效。
viewGroup.add(view, new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3326 次 |
| 最近记录: |