我是android的初学者。我正在尝试实施RecyclerView
。我在我的活动中创建了一个视图,然后将视图传递给适配器构造函数,如下所示。
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout lv = new LinearLayout(this);
lv.setLayoutParams(layoutParams);
View v = new TextView(this);
v.setLayoutParams(layoutParams);
v.setId(R.id.reservedId);
lv.addView(v);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLinearLayoutManager);
// Passing the created view to the adapter.
AdapterRecylerView mAdapter = new AdapterRecylerView(this, lv);
recyclerView.setAdapter(mAdapter);
在适配器中,我创建了一个公共视图,并将传递的视图分配给该视图并访问onCreateViewHolder
中的视图,如下所示。
private class AdapterRecylerView extends RecyclerView.Adapter<AdapterRecylerView.ViewHolder>{
private Context context;
private View lv;
public AdapterRecylerView(Context context, LinearLayout lv) {
this.context = context;
this.lv = lv;
}
@Override
public AdapterRecylerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Using the passed view
ViewHolder vh = new ViewHolder(lv);
return vh;
}
@Override
public void onBindViewHolder(AdapterRecylerView.ViewHolder holder, int position) {
holder.mTextView.setText(""+(position+1));
}
@Override
public int getItemCount() {
return 100;
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.reservedId);
}
}
}
当我运行代码时,我无法看到视图。看起来视图占据了整个父级。第一个文本显示在左上角,最后一个文本显示在左下角,如下所示。当我滚动时无法查看某些视图。
我不知道是什么问题。我做错了什么。任何人都可以帮我解决这个问题。
答案 0 :(得分:0)
您的问题源自使用单个View实例/对象的所有ViewHolder
。您需要为每个ViewHolder
实例创建一个单独的View实例。