我已经创建了一个您要完成的工作示例。您遇到的错误的根源主要是您不了解视图回收。我现在不打算向您解释整个过程,但是无论如何,下面是示例:
对于示例,我为每一行使用了这种布局:
<?xml version="1.0" encoding="utf-8"?><frameLayout android:id="@+id/background" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="80dp"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center"/></frameLayout>
我使用了这个模型:
public class ExampleModel { private final int mColor; private final String mText; public ExampleModel(int color, String text) { mColor = color; mText = text; } public int getColor() { return mColor; } public String getText() { return mText; }}这个视图持有者:
public class ExampleViewHolder extends RecyclerView.ViewHolder { private final frameLayout mBackground; private final TextView mTextView; public ExampleViewHolder(View itemView) { super(itemView); mBackground = (frameLayout) itemView.findViewById(R.id.background); mTextView = (TextView) itemView.findViewById(R.id.textView); } public void bind(ExampleModel model) { mBackground.setBackgroundColor(model.getColor()); mTextView.setText(model.getText()); }}如您所见,没有什么特别的,
Adapter实现同样简单:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> { private final LayoutInflater mInflater; private final List<ExampleModel> mModels; public ExampleAdapter(Context context, List<ExampleModel> models) { mInflater = LayoutInflater.from(context); mModels = models; } @Override public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View itemView = mInflater.inflate(R.layout.item_example, parent, false); return new ExampleViewHolder(itemView); } @Override public void onBindViewHolder(ExampleViewHolder holder, int position) { final ExampleModel model = mModels.get(position); holder.bind(model); } @Override public int getItemCount() { return mModels.size(); }}您可以像这样使用整个内容:
final Random mRandom = new Random(System.currentTimeMillis());@Overridepublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); final List<ExampleModel> models = new ArrayList<>(); for (int i = 0; i < 100; i++) { final int randomColor = generateRandomPastelColor(); models.add(new ExampleModel(randomColor, String.valueOf(i))); } final ExampleAdapter adapter = new ExampleAdapter(getActivity(), models); recyclerView.setAdapter(adapter);}public int generateRandomPastelColor() { final int baseColor = Color.WHITE; final int red = (Color.red(baseColor) + mRandom.nextInt(256)) / 2; final int green = (Color.green(baseColor) + mRandom.nextInt(256)) / 2; final int blue = (Color.blue(baseColor) + mRandom.nextInt(256)) / 2; return Color.rgb(red, green, blue);}这应该可以满足您的需求,您可以将其用作实现您的的示例
Adapter。



