首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >迭代RecyclerView

迭代RecyclerView
EN

Stack Overflow用户
提问于 2022-04-24 23:13:41
回答 2查看 219关注 0票数 0

我想循环遍历所有的CardViews,并通过单击按钮改变TextView在单个CardView项目中的文本和颜色。下面的代码似乎产生了所需的结果,但我不确定它是否是最有效的代码,甚至是准确的(索引)。

代码语言:javascript
运行
复制
// CustomAdapter

import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {

    private Context context;
    private List<MyModel> list;

    public CustomAdapter(Context context, List<MyModel> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        holder.textName.setText(list.get(position).getName());
        holder.textAge.setText(String.valueOf(list.get(position).getAge()));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

}

//CustomViewHolder

import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class CustomViewHolder extends RecyclerView.ViewHolder {

    public TextView textName, textAge;

    public CustomViewHolder(@NonNull View itemView) {
        super(itemView);

        textName = itemView.findViewById(R.id.textName);
        textAge = itemView.findViewById(R.id.textAge);
    }

}
MainActivity

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    List<MyModel> myModelList;
    CustomAdapter customAdapter;

    private Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadData();
    }

    private void loadData() {
        recyclerView = findViewById(R.id.recycler_main);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));

        myModelList = new ArrayList<>();

        myModelList.add(new MyModel("Joe", 21));
        myModelList.add(new MyModel("Jane", 26));
        myModelList.add(new MyModel("Kyle", 19));
        myModelList.add(new MyModel("Scott", 30));

        customAdapter = new CustomAdapter(this, myModelList);
        recyclerView.setAdapter(customAdapter);
    }

    public void onClickBtn(View v)
    {
        String searchString = "Kyle";

        for (int x = recyclerView.getChildCount(), i = 0; i < x; ++i) {
            RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(recyclerView.getChildAt(i));
            TextView txtName = holder.itemView.findViewById(R.id.textName);

            if (txtName.getText().toString().equals(searchString.toString())) {
                txtName.setText("Found " + txtName.getText().toString());
                txtName.setTextColor(Color.GREEN);
                customAdapter.notifyItemChanged(x);
            }
        }
    }

}

//MyModel

public class MyModel {

    String name = "";
    int age = 0;

    public MyModel(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

重要的是,我在按钮单击事件中迭代列表。以后要更改的功能。非常感谢你的任何建议和反馈。更新。必须是索引或其他相关问题。当我的ArrayList包含更多、更多的项目和按钮时,很多未找到的行文本和颜色都会被更改。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-27 10:13:25

试试这个适配器:

代码语言:javascript
运行
复制
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {

private Context context;
private List<MyModel> list;
private String searchString = "";

public CustomAdapter(Context context, List<MyModel> list) {
    this.context = context;
    this.list = list;
}

@NonNull
@Override
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
}

@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
    holder.textAge.setText(String.valueOf(list.get(position).getAge()));
    if(list.get(position).getName().equals(searchString)){
        holder.textName.setText("Found " + list.get(position).getName());
        holder.textName.setTextColor(Color.GREEN);
    } else {
        holder.textName.setText(list.get(position).getName());
        holder.textName.setTextColor(Color.BLACK);
    }
}

@Override
public int getItemCount() {
    return list.size();
}

public void setNewSearchString(String searchString) {
    this.searchString = searchString;
    notifyDataSetChanged();
}
}

然后按一下按钮:

代码语言:javascript
运行
复制
public void onClickBtn(View v)
{
    customAdapter.setNewSearchString("Kyle");
}

对于多个搜索,适配器:

代码语言:javascript
运行
复制
public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {

private Context context;
private List<MyModel> list;
//private String searchString = "";
private ArrayList<String> arraySearchStrings = new ArrayList<>();

public CustomAdapter(Context context, List<MyModel> list) {
    this.context = context;
    this.list = list;
}

@NonNull
@Override
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
}

@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
    holder.textAge.setText(String.valueOf(list.get(position).getAge()));
    boolean found = false;
    for (String searchString : arraySearchStrings) {
        if (list.get(position).getName().equals(searchString)) {
            found = true;
            break;
        }
    }
    if (found) {
        holder.textName.setText("Found " + list.get(position).getName());
        holder.textName.setTextColor(Color.GREEN);
    } else {
        holder.textName.setText(list.get(position).getName());
        holder.textName.setTextColor(Color.BLACK);
    }
}

@Override
public int getItemCount() {
    return list.size();
}

public void setNewSearchString(String searchString) {
    //this.searchString = searchString;
    arraySearchStrings.add(searchString);
    notifyDataSetChanged();
}

public void resetSearchString() {
    arraySearchStrings.clear();
    notifyDataSetChanged();
}
}

按钮单击:

代码语言:javascript
运行
复制
public void onClickBtn(View v)
{
    customAdapter.setNewSearchString("Kyle");
    customAdapter.setNewSearchString("Steve");
    customAdapter.setNewSearchString("Joe");
}

备选回答者:

代码语言:javascript
运行
复制
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

private Context context;
private List<MyModel> list;
private ArrayList<String> arraySearchStrings = new ArrayList<>();
private ArrayList<Boolean> arrayFound = new ArrayList<>();
private int[] arrayFoundCount;
private int foundTotalCount = 0;

public CustomAdapter(Context context, List<MyModel> list) {
    this.context = context;
    this.list = list;
    arrayFoundCount = new int[list.size()];
    for (int i = 0; i < list.size(); i++) {
        arrayFound.add(false);
        arrayFoundCount[i] = 0;
    }
}

@NonNull
@Override
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
}

@Override
public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
    holder.textAge.setText(String.valueOf(list.get(position).getAge()));
    holder.textCount.setText(String.valueOf(arrayFoundCount[position]));
    if (arrayFound.get(position)) {
        holder.textName.setText("Found " + list.get(position).getName());
        holder.textName.setTextColor(Color.GREEN);
    } else {
        holder.textName.setText(list.get(position).getName());
        holder.textName.setTextColor(Color.BLACK);
    }
}

@Override
public int getItemCount() { return list.size(); }

public class CustomViewHolder extends RecyclerView.ViewHolder {

    public TextView textName, textAge, textCount;

    public CustomViewHolder(@NonNull View itemView) {
        super(itemView);
        textName = itemView.findViewById(R.id.textName);
        textAge = itemView.findViewById(R.id.textAge);
        textCount = itemView.findViewById(R.id.textCount);
    }
}

private int countFoundNameInList() {

    int count = 0;
    boolean found;
    MyModel model;

    arrayFound.clear();
    for (int i = 0; i < list.size(); i++) {
        model = list.get(i);
        found = false;
        for (String searchString : arraySearchStrings) {
            if (model.getName().equals(searchString)) {
                found = true;
                arrayFoundCount[i] = arrayFoundCount[i]++;
                count++;
                break;
            }
        }
        arrayFound.add(found);
    }
    return count;
}

public void setNewSearchString(String searchString) {
    arraySearchStrings.add(searchString);
    int newCount = countFoundNameInList();
    if (newCount > foundTotalCount) {
        Toast.makeText(context, searchString + " found.", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(context, "Error: Nothing found!!", Toast.LENGTH_LONG).show();
    }
    foundTotalCount = newCount;
    notifyDataSetChanged();
}
}
票数 1
EN

Stack Overflow用户

发布于 2022-04-25 04:47:05

我不认为这个代码会给你准确的结果。您必须想出不同的逻辑,在您的逻辑中,您正在搜索静态名称,我确信这只是为了演示目的。稍后,您将使用用户输入字符串实现。因此,根据我的意见,您可以在适配器中创建变量,即搜索模式是on或off --当用户开始搜索时,使searchMode打开;与在您的viewHolder类中搜索set searchMode Off时相同,您可以在关闭状态的searchMode上进行更新。您可以创建2个列表,1表示主列表,秒表示搜索列表,当用户开始搜索时,您必须使用搜索字符串过滤主列表,然后将其设置为searchedList,然后将searchMode设置为On,然后将其更新到适配器。rest将处理您的适配器。不需要一个一个地从你的名单上修改。

根据我的意见,我在这里添加所需的更改。

您的自定义适配器

代码语言:javascript
运行
复制
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

   private Context context;
   private List<MyModel> list;
   private Boolean isSearchModeOn = false;

   public CustomAdapter(@NonNull Context context, @NonNull List<MyModel> list) {
      this.context = context;
      this.list = list;
   }

   @NonNull
   @Override
   public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.single_items, parent, false));
   }

   @Override
   public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
      if (isSearchModeOn){
         holder.textName.setText("Found " + list.get(position).getName());
         holder.textName.setTextColor(Color.GREEN);
      }else {
         holder.textName.setText(list.get(position).getName());
         //Also set Here normal text color
      }
      holder.textAge.setText(String.valueOf(list.get(position).getAge()));
   }

   @SuppressLint("NotifyDataSetChanged")
   public void updateList(@NonNull List<MyModel> searchedList){
      list = searchedList;
      notifyDataSetChanged();
   }

   @SuppressLint("NotifyDataSetChanged")
   public void setSearchMode(@NonNull Boolean isOn){
      isSearchModeOn = isOn;
      notifyDataSetChanged();
   }

   @Override
   public int getItemCount() {
      return list.size();
   }

   public class CustomViewHolder extends RecyclerView.ViewHolder {

      @NonNull
      public TextView textName, textAge;

      public CustomViewHolder(@NonNull View itemView) {
         super(itemView);

         textName = itemView.findViewById(R.id.textName);
         textAge = itemView.findViewById(R.id.textAge);
      }

   }

}

MainActivity

代码语言:javascript
运行
复制
public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    List<MyModel> myModelList;
    List<MyModel> searchedList;
    CustomAdapter customAdapter;

    @Override
    protected void onCreate(@NonNull Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        loadData();
    }

    private void loadData() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));

        myModelList = new ArrayList<>();

        myModelList.add(new MyModel("Joe", 21));
        myModelList.add(new MyModel("Jane", 26));
        myModelList.add(new MyModel("Kyle", 19));
        myModelList.add(new MyModel("Scott", 30));

        customAdapter = new CustomAdapter(this, myModelList);
        recyclerView.setAdapter(customAdapter);
    }

    public void onClickBtn(@NonNull View v)
    {
        String searchString = "Kyle";
        searchedList = new ArrayList<>();

        for (int x = myModelList.size(), i = 0; i < x; ++i) {
            if (myModelList.get(i).getName().equals(searchString)){
                searchedList.add(myModelList.get(i));
            }
        }
        customAdapter.updateList(searchedList);
        customAdapter.setSearchMode(true);
    }
}

我主要是用kotlin开发的,所以在这段代码中可能会出现一些文本错误。您可以检查此需求的逻辑。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71993078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档