在包含字符串名称和字符串子文本的 RecyclerView 中搜索字符串名称时出现问题
Problem with searching String name in RecyclerView that contains String name and String subtext
好吧,我有一个 RecyclerView,它的 Items 包含名称和潜台词。我创建了一个 class MyObject 来填充它们。使用我的适配器,我正在填充 RecyclerView。我想在我的 RecyclerView 中搜索一个字符串名称,并且该应用程序显示了名称与搜索匹配的所有项目(包括名称和潜台词)。但我不知道我该怎么做。对我来说真的很难解释,所以你可能会从我的代码中理解更多。如果您需要,我可以提供更多信息或代码。
(抱歉有些俄语文本,但这并不重要)。
MainActivity.java代码:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
DatabaseHelper myDB;
MyAdapter mAdapter;
RecyclerView mRecyclerView;
int year,month,day;
int count;
ArrayList<MyObject> myObjects;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
Cursor cursor = myDB.forCount(year,month,day);
count = cursor.getCount();
if (count != 0) {
alertWhenDelete(count);}
myDB.deleteIstekshiySrokGodnosy(year,month,day);
mRecyclerView = findViewById(R.id.recyclerView);
myObjects = new ArrayList<>();
Cursor data = myDB.getListContents();
if(data.getCount() == 0){
Toast.makeText(this, "Ваш список товаров пуст!",Toast.LENGTH_LONG).show();
}else{
while(data.moveToNext()){
myObjects.add(new MyObject(data.getString(1), "Дата окончания срока годности: "+data.getInt(4)+"."+data.getInt(3)+"."+data.getInt(2)));
mAdapter = new MyAdapter();
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mAdapter.updateData(myObjects);
}
}
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
...
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
String userInput = newText.toLowerCase();
ArrayList<MyObject> newList = new ArrayList<>();
for (String name : myObjects){
if(name.toLowerCase().contains(userInput)) {
newList.add(name);
}
}
mAdapter.updateData(newList);
return true;
}
}
MyAdapter.java代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements View.OnClickListener {
private ArrayList<MyObject> mItems = new ArrayList<>();
public String nametext;
DatabaseHelper myDB;
int idactivity;
String nameactivity;
int yearactivity;
int monthactivity;
int dayactivity;
int priceactivity;
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
MyViewHolder vh=new MyViewHolder(view);
view.setOnClickListener(this);
return vh;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.bindData(getItem(position));
}
@Override
public int getItemCount() {
return mItems.size();
}
public void updateData(ArrayList<MyObject> items) {
mItems = new ArrayList<>(items);
notifyDataSetChanged();
}
private MyObject getItem(int position) {
if (position >= 0 && position < mItems.size())
return mItems.get(position);
return null;
}
@Override
public void onClick(View v) {
idactivity = 0;
nameactivity = null;
yearactivity = 0;
monthactivity = 0;
dayactivity = 0;
priceactivity = 0;
myDB = new DatabaseHelper(v.getContext());
TextView clickedName=(TextView)v.findViewById(R.id.title);
nametext = clickedName.getText().toString();
Toast.makeText(v.getContext(),nametext,Toast.LENGTH_LONG).show();
Cursor c = myDB.showDataonSelect(nametext);
if(c.moveToFirst()) {
idactivity = c.getInt(0) ;
nameactivity = c.getString(1) ;
yearactivity = c.getInt(2) ;
monthactivity = c.getInt(3) ;
dayactivity = c.getInt(4);
priceactivity = c.getInt(5);
}
Log.d("TAG",
"ID = " + idactivity +
", name = " + nameactivity +
", year = " + yearactivity +
", month = " + monthactivity +
", day = " + dayactivity +
", price = " + priceactivity);
Intent myIntent = new Intent(v.getContext(), Main3Activity.class);
Bundle extras = new Bundle();
extras.putString("Name", nameactivity);
extras.putInt("Year", yearactivity);
extras.putInt("Month", monthactivity);
extras.putInt("Day", dayactivity);
extras.putInt("Price", priceactivity);
myIntent.putExtras(extras);
v.getContext().startActivity(myIntent);
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView subTitle;
MyViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
subTitle = itemView.findViewById(R.id.sub_title);
}
void bindData(MyObject myObject) {
if (myObject == null)
return;
title.setText(myObject.title);
subTitle.setText(myObject.subTitle);
}
}
}
MyObject.java代码:
public class MyObject {
public String title;
public String subTitle;
public MyObject(String title, String subTitle) {
this.title = title;
this.subTitle = subTitle;
}
}
当我在搜索中搜索项目名称时,我希望看到该应用程序向我显示名称与搜索及其潜台词相匹配的项目。
使用可过滤
取另一个List来保留实际列表,用myObjects初始化它,并在更新列表数据时在constructor/中设置值。
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
implements View.OnClickListener, Filterable {
private List<MyObject> myObjects;
private List<MyObject> reservedList;
//....
//remove mItems from your class replace it with myObjects
public MyAdapter(List<MyObject> myObjects){
this.myObjects = myObjects;
this.reservedList = myObjects;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
if (!charString.isEmpty()) {
List<MyObject> filteredList = new ArrayList<>();
for (MyObject row : reservedList) {
if (row.title.toLowerCase().contains(charString) || row.subTitle.toLowerCase().contains(charString)) {
filteredList.add(row);
}
}
myObjects = filteredList;
} else {
myObjects = reservedList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = myObjects;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
myObjects = (ArrayList<MyObject>) filterResults.values;
notifyDataSetChanged();
}
};
}
这样设置适配器
while(data.moveToNext()){
myObjects.add(new MyObject(data.getString(1), "Дата окончания срока годности: "+data.getInt(4)+"."+data.getInt(3)+"."+data.getInt(2)));
mAdapter = new MyAdapter(myObjects);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
// mAdapter.updateData(myObjects); you don't need this
}
现在在您的 activity 上传递您要搜索的字符串 mAdapter.getFilter().filter(query);
@Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
好吧,我有一个 RecyclerView,它的 Items 包含名称和潜台词。我创建了一个 class MyObject 来填充它们。使用我的适配器,我正在填充 RecyclerView。我想在我的 RecyclerView 中搜索一个字符串名称,并且该应用程序显示了名称与搜索匹配的所有项目(包括名称和潜台词)。但我不知道我该怎么做。对我来说真的很难解释,所以你可能会从我的代码中理解更多。如果您需要,我可以提供更多信息或代码。 (抱歉有些俄语文本,但这并不重要)。
MainActivity.java代码:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
DatabaseHelper myDB;
MyAdapter mAdapter;
RecyclerView mRecyclerView;
int year,month,day;
int count;
ArrayList<MyObject> myObjects;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
Cursor cursor = myDB.forCount(year,month,day);
count = cursor.getCount();
if (count != 0) {
alertWhenDelete(count);}
myDB.deleteIstekshiySrokGodnosy(year,month,day);
mRecyclerView = findViewById(R.id.recyclerView);
myObjects = new ArrayList<>();
Cursor data = myDB.getListContents();
if(data.getCount() == 0){
Toast.makeText(this, "Ваш список товаров пуст!",Toast.LENGTH_LONG).show();
}else{
while(data.moveToNext()){
myObjects.add(new MyObject(data.getString(1), "Дата окончания срока годности: "+data.getInt(4)+"."+data.getInt(3)+"."+data.getInt(2)));
mAdapter = new MyAdapter();
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mAdapter.updateData(myObjects);
}
}
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
...
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
String userInput = newText.toLowerCase();
ArrayList<MyObject> newList = new ArrayList<>();
for (String name : myObjects){
if(name.toLowerCase().contains(userInput)) {
newList.add(name);
}
}
mAdapter.updateData(newList);
return true;
}
}
MyAdapter.java代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements View.OnClickListener {
private ArrayList<MyObject> mItems = new ArrayList<>();
public String nametext;
DatabaseHelper myDB;
int idactivity;
String nameactivity;
int yearactivity;
int monthactivity;
int dayactivity;
int priceactivity;
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
MyViewHolder vh=new MyViewHolder(view);
view.setOnClickListener(this);
return vh;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.bindData(getItem(position));
}
@Override
public int getItemCount() {
return mItems.size();
}
public void updateData(ArrayList<MyObject> items) {
mItems = new ArrayList<>(items);
notifyDataSetChanged();
}
private MyObject getItem(int position) {
if (position >= 0 && position < mItems.size())
return mItems.get(position);
return null;
}
@Override
public void onClick(View v) {
idactivity = 0;
nameactivity = null;
yearactivity = 0;
monthactivity = 0;
dayactivity = 0;
priceactivity = 0;
myDB = new DatabaseHelper(v.getContext());
TextView clickedName=(TextView)v.findViewById(R.id.title);
nametext = clickedName.getText().toString();
Toast.makeText(v.getContext(),nametext,Toast.LENGTH_LONG).show();
Cursor c = myDB.showDataonSelect(nametext);
if(c.moveToFirst()) {
idactivity = c.getInt(0) ;
nameactivity = c.getString(1) ;
yearactivity = c.getInt(2) ;
monthactivity = c.getInt(3) ;
dayactivity = c.getInt(4);
priceactivity = c.getInt(5);
}
Log.d("TAG",
"ID = " + idactivity +
", name = " + nameactivity +
", year = " + yearactivity +
", month = " + monthactivity +
", day = " + dayactivity +
", price = " + priceactivity);
Intent myIntent = new Intent(v.getContext(), Main3Activity.class);
Bundle extras = new Bundle();
extras.putString("Name", nameactivity);
extras.putInt("Year", yearactivity);
extras.putInt("Month", monthactivity);
extras.putInt("Day", dayactivity);
extras.putInt("Price", priceactivity);
myIntent.putExtras(extras);
v.getContext().startActivity(myIntent);
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView subTitle;
MyViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
subTitle = itemView.findViewById(R.id.sub_title);
}
void bindData(MyObject myObject) {
if (myObject == null)
return;
title.setText(myObject.title);
subTitle.setText(myObject.subTitle);
}
}
}
MyObject.java代码:
public class MyObject {
public String title;
public String subTitle;
public MyObject(String title, String subTitle) {
this.title = title;
this.subTitle = subTitle;
}
}
当我在搜索中搜索项目名称时,我希望看到该应用程序向我显示名称与搜索及其潜台词相匹配的项目。
使用可过滤
取另一个List来保留实际列表,用myObjects初始化它,并在更新列表数据时在constructor/中设置值。
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
implements View.OnClickListener, Filterable {
private List<MyObject> myObjects;
private List<MyObject> reservedList;
//....
//remove mItems from your class replace it with myObjects
public MyAdapter(List<MyObject> myObjects){
this.myObjects = myObjects;
this.reservedList = myObjects;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
if (!charString.isEmpty()) {
List<MyObject> filteredList = new ArrayList<>();
for (MyObject row : reservedList) {
if (row.title.toLowerCase().contains(charString) || row.subTitle.toLowerCase().contains(charString)) {
filteredList.add(row);
}
}
myObjects = filteredList;
} else {
myObjects = reservedList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = myObjects;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
myObjects = (ArrayList<MyObject>) filterResults.values;
notifyDataSetChanged();
}
};
}
这样设置适配器
while(data.moveToNext()){
myObjects.add(new MyObject(data.getString(1), "Дата окончания срока годности: "+data.getInt(4)+"."+data.getInt(3)+"."+data.getInt(2)));
mAdapter = new MyAdapter(myObjects);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
// mAdapter.updateData(myObjects); you don't need this
}
现在在您的 activity 上传递您要搜索的字符串 mAdapter.getFilter().filter(query);
@Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}