如何在android的recyclerview中搜索数据
Posted
技术标签:
【中文标题】如何在android的recyclerview中搜索数据【英文标题】:How to search data in recylerview in android 【发布时间】:2020-04-27 23:57:22 【问题描述】:我的所有代码都运行成功,但我想添加 Searchview。 我尝试了很多方法。
edittext 文本更改应用程序崩溃时。
我也应用了 try cathed 方法,但我没有看到任何错误只是应用程序崩溃并转到主要活动。 这是我的 listadapter 类代码。
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> implements Filterable
ArrayList<MyListData> myListDataArrayList;
String packaging = "";
private MyListData[] listdata;
private Context context;
private CustomFilter filter;
public MyListAdapter(ArrayList<MyListData> horizontalList, Context context)
this.myListDataArrayList = horizontalList;
this.context = context;
// RecyclerView recyclerView;
public MyListAdapter(MyListData[] listdata)
this.listdata = listdata;
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
@Override
public void onBindViewHolder(final ViewHolder holder, final int position)
final MyListData myListData = myListDataArrayList.get(position);
holder.tv_hhid.setText("HHID : " + myListData.getHh_id());
holder.tv_respid.setText("Resp_ID : " + myListData.getResp_id());
holder.tv_firstname.setText(myListData.getFirst_name());
// holder.tv_firstname.setText(myListData.getFirst_name()+" " + myListData.getLast_name());
holder.tv_lastname.setText(myListData.getLast_name());
holder.relativeLayout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
// Toast.makeText(view.getContext(), "click on item: " + myListData.getHh_id(), Toast.LENGTH_LONG).show();
Intent intent = new Intent(view.getContext(), Section_Mandatory.class);
intent.putExtra("hhid", myListData.getHh_id());
intent.putExtra("resp_id", myListData.getResp_id());
view.getContext().startActivity(intent);
);
@Override
public int getItemCount()
return myListDataArrayList.size();
@Override
public Filter getFilter()
if (filter == null)
filter = new CustomFilter(myListDataArrayList, this);
return filter;
public static class ViewHolder extends RecyclerView.ViewHolder
public TextView tv_hhid, tv_respid, tv_firstname, tv_lastname;
public RelativeLayout relativeLayout;
public ViewHolder(View itemView)
super(itemView);
this.tv_hhid = itemView.findViewById(R.id.tv_hhid);
this.tv_respid = itemView.findViewById(R.id.tv_respid);
this.tv_firstname = itemView.findViewById(R.id.tv_firstname);
this.tv_lastname = itemView.findViewById(R.id.tv_lastname);
relativeLayout = itemView.findViewById(R.id.relativeLayout);
public class CustomFilter extends Filter
MyListAdapter adapter;
List<MyListData> filterList;
public CustomFilter(List<MyListData> filterList, MyListAdapter adapter)
this.adapter = adapter;
this.filterList = filterList;
@Override
protected FilterResults performFiltering(CharSequence constraint)
FilterResults results = new FilterResults();
return results;
@Override
protected void publishResults(CharSequence constraint, FilterResults results)
adapter.myListDataArrayList = (ArrayList<MyListData>) results.values;
adapter.notifyDataSetChanged();
这是我的 Getter 和 Setter 类。
public class MyListData
private String hh_id;
private String resp_id;
private String first_name;
private String last_name;
///public MyListData(String hh_id, String resp_id, String first_name, String last_name)
public MyListData()
this.hh_id = hh_id;
this.resp_id = resp_id;
this.first_name = first_name;
this.last_name = last_name;
public String getHh_id()
return hh_id;
public void setHh_id(String hh_id)
this.hh_id = hh_id;
public String getResp_id()
return resp_id;
public void setResp_id(String resp_id)
this.resp_id = resp_id;
public String getFirst_name()
return first_name;
public void setFirst_name(String first_name)
this.first_name = first_name;
public String getLast_name()
return last_name;
public void setLast_name(String last_name)
this.last_name = last_name;
这是我的活动课。
public class Edit_Form extends AppCompatActivity
DatabaseAdapter databaseAccess;
RecyclerView recyclerView;
TextView textView;
LinearLayoutManager manager;
ArrayList<MyListData> myListDataArrayList;
MyListAdapter adapter;
EditText searchview;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit__form);
recyclerView = findViewById(R.id.recyclerView);
textView = findViewById(R.id.txtNoDataFound);
searchview = findViewById(R.id.Search_view_);
manager = new LinearLayoutManager(Edit_Form.this, RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
myListDataArrayList = new ArrayList<>();
readData();
searchview.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
@Override
public void afterTextChanged(Editable s)
try
String text = searchview.getText().toString().toLowerCase();
if (adapter != null)
adapter.getFilter().filter(text);
catch (Exception e)
Toast.makeText(Edit_Form.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
);
void readData()
Cursor cursor;
databaseAccess = new DatabaseAdapter(Edit_Form.this);
databaseAccess.Open();
cursor = databaseAccess.editform();
if (cursor != null && cursor.getCount() > 0)
recyclerView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
if (cursor.moveToFirst())
do
String str_hhid = (cursor.getString(cursor.getColumnIndex("hhid_id")));
String str_Resp_id = (cursor.getString(cursor.getColumnIndex("resp_id")));
String str_first_name = (cursor.getString(cursor.getColumnIndex("q1_fname")));
String str_last_name = (cursor.getString(cursor.getColumnIndex("q1_lname")));
MyListData myListData = new MyListData();
myListData.setHh_id(str_hhid);
myListData.setResp_id(str_Resp_id);
myListData.setFirst_name(str_first_name);
myListData.setLast_name(str_last_name);
myListDataArrayList.add(myListData);
while (cursor.moveToNext());
cursor.close();
if (myListDataArrayList != null && myListDataArrayList.size() > 0)
adapter = new MyListAdapter(myListDataArrayList, Edit_Form.this);
recyclerView.setAdapter(adapter);
else
textView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
// Toast.makeText(Edit_Form.this, "No Data Found ", Toast.LENGTH_SHORT).show();
这是我的 recyclerview xml 活动。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:background="@color/white_color"
android:orientation="vertical"
tools:context=".Edit_Form.Edit_Form">
<EditText
android:id="@+id/Search_view_"
android:layout_
android:layout_
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:hint="Search"
android:padding="20dp"
android:textColorHint="#606060"
android:textSize="18sp"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_
android:layout_
android:layout_marginLeft="24dp"
android:layout_marginTop="12dp"
android:layout_marginRight="24dp"
android:layout_marginBottom="12dp"
android:visibility="gone" />
<TextView
android:id="@+id/txtNoDataFound"
android:layout_
android:layout_
android:layout_gravity="center"
android:fontFamily="serif"
android:gravity="center"
android:text="No Data found."
android:textColor="@color/colorPrimary"
android:textSize="18sp"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
这是我的列表项内容 xml 活动..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/relativeLayout"
android:layout_
android:layout_
android:layout_marginTop="4dp"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_
android:layout_
android:layout_margin="5dp"
android:background="@color/white_color"
android:focusable="true"
app:cardBackgroundColor="@color/white_color"
app:cardCornerRadius="8dp"
app:cardElevation="8dp">
<LinearLayout
android:layout_
android:layout_
android:layout_marginTop="1dp"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_
android:layout_
android:layout_margin="0dp"
android:background="@color/white_color"
android:focusable="true"
app:cardBackgroundColor="@color/white_color"
app:cardCornerRadius="8dp"
app:cardElevation="8dp">
<LinearLayout
android:layout_
android:layout_
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_hhid"
android:layout_
android:layout_
android:layout_marginLeft="8dp"
android:gravity="center"
android:paddingLeft="16dp"
android:paddingTop="4dp"
android:paddingRight="16dp"
android:paddingBottom="4dp"
android:text="HH ID :"
android:textAllCaps="false"
android:textColor="#96144C"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_respid"
android:layout_
android:layout_
android:layout_marginLeft="8dp"
android:gravity="center"
android:paddingLeft="16dp"
android:paddingTop="4dp"
android:paddingRight="16dp"
android:paddingBottom="4dp"
android:text="Resp ID :"
android:textAllCaps="false"
android:textColor="#4CAF50"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_
android:layout_
android:layout_margin="0.5dp"
android:background="@color/white_color"
android:focusable="true"
app:cardBackgroundColor="@color/white_color"
app:cardCornerRadius="8dp"
app:cardElevation="8dp">
<LinearLayout
android:layout_
android:layout_
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_firstname"
android:layout_
android:layout_
android:layout_marginLeft="8dp"
android:gravity="center"
android:paddingLeft="16dp"
android:paddingTop="4dp"
android:paddingRight="16dp"
android:paddingBottom="4dp"
android:text="First Name :"
android:textAllCaps="false"
android:textColor="#96144C"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_lastname"
android:layout_
android:layout_
android:gravity="center"
android:paddingTop="4dp"
android:paddingRight="16dp"
android:paddingBottom="4dp"
android:text="Last Name :"
android:textColor="#4CAF50"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
提前致谢
【问题讨论】:
分享你的堆栈跟踪 如果发生崩溃,您应该从 logcat 中发布相关部分,但除外。 logcat 删除了所有数据并返回仅显示此内容。 2020-01-10 15:41:07.652 2536-2555/waceem.virk.backcheckqss E/MemoryLeakMonitorManager:MemoryLeakMonitor.jar 不存在! 2020-01-10 15:41:07.654 2536-2536/waceem.virk.backcheckqss E/Minikin:无法获取 cmap 表大小! 【参考方案1】:您可以在 Activity/Fragment 类中添加此方法
void filter(String text)
ArrayList<ModelClass> model=new ArrayList<>();
for(ModelClass name: model)
//or use .equal(text) with you want equal match
//use .toLowerCase() for better matches
if(name.getName().toLowerCase().contains(text.toLowerCase()))
model.add(name);
//update recyclerview
adapter.updateList(model);
ModelClass 是你的 POJO 类,在你的情况下是 MyListData
像这样使用这个方法
searchView.addTextChangedListener(new TextWatcher()
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
filter(s.toString());
// TODO Auto-generated method stub
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
// TODO Auto-generated method stub
@Override
public void afterTextChanged(Editable s)
// filter your list from your input
//you can use runnable postDelayed like 500 ms to delay search text
);
并在适配器中添加以下方法:
public void updateList(List<ModelClass> list)
modelList= list;
notifyDataSetChanged();
【讨论】:
搜索视图不起作用它没有执行任何工作我输入任何单词它什么都不做也没有给出任何错误 实际上它在我的情况下工作。你能分享更新的代码吗?【参考方案2】:我认为你应该在 onTextChanged 方法中设置 adapter.getFilter().filter(text)。
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
adapter.getFilter().filter(cs);
【讨论】:
不,它不工作。但是感谢您的尝试以上是关于如何在android的recyclerview中搜索数据的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Android 的 RecyclerView 中显示来自 Firestore 的数据?
Android:如何使用 RecyclerView 实现图片库
如何在 Android Studio 中禁用 recyclerview 特定数据?
如何在 recyclerview 适配器中将动态视图添加到 android 布局