动态添加一个视图到 RecyclerView

Add a view dynamically to the RecyclerView

我一直在开发一个列表视图,在列表视图(卡片视图)的每一行上我有一个水平滚动视图,我在滚动视图上添加了一些视图(动态视图)(这是动态的,视图计数每一行都不同) 但是当我向下滚动或向上滚动时,适配器会在 scrool 视图上添加额外的视图(我的意思是例如它应该添加 2 个视图并且它添加了但是当向下或向上滚动时它也添加了 2 个 extara 视图)

我不知道如何解决这个问题。

我的代码:

@Override
public void onBindViewHolder(SicknessResulteHolder holder, int position) {

    //Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView
    /**********************************************************************************************************/

    List<String> user_symptoms = new ArrayList<String>();
    for (int i = 0 ; i<frag_recognize_1.list.size() ; i++){

        for (int j = 0 ; j< list.get(position).user_symptoms.size() ; j++){
            if (list.get(position).user_symptoms.get(j) == frag_recognize_1.list.get(i).getSymptoms_id()){
                user_symptoms.add(frag_recognize_1.list.get(i).getTitle());
            }
        }
    }
    /**********************************************************************************************************/


    if (list.get(position).addView){
        for (int i = 0 ; i < list.get(position).user_symptoms.size() ; i++){

            LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
            LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.symptoms_row,null,false);
            TextView textView = (TextView) linearLayout.findViewById(R.id.textView);
            textView.setText(String.valueOf(user_symptoms.get(i)));
            textView.setTextColor(Color.WHITE);

            holder.scrollSymptoms.addView(linearLayout);
        }
        list.get(position).setAddView(false);
    }





}

那是因为你是在ViewHolder绑定的时候添加view的。尝试在创建 View holder 时执行此操作。

@Override
public YourAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//your addView goes here
}