所以,我在Android Studio中制作了一个包含MainView活动中ListView的应用程序,并且我在Android中使用SearchView来过滤搜索结果。我的ListView包含图像和文本。我想按文字搜索。请参阅以下代码。当我按下搜索按钮并输入内容时,列表视图中看不到任何内容。请看一下并提出一个合理的解决方案。
这是我的MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("temples");
ListView templeListView;
SearchView searchView;
List<Temple> temples = new ArrayList<>();
ItemAdapter itemAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Navigation Drawer Logic
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Initializing elements
templeListView = findViewById(R.id.templeListView);
//Getting Database Items
templeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Temple currentTemple = temples.get(position);
Intent intent = new Intent(MainActivity.this, TempleDetails.class);
intent.putExtra("templeName",currentTemple.getTempleName());
intent.putExtra("templeAddress",currentTemple.getTempleAddress());
intent.putExtra("templeImageURI",currentTemple.getTempleImageURI());
intent.putExtra("latitude",currentTemple.getLatitude());
intent.putExtra("longitude",currentTemple.getLongitude());
startActivity(intent);
}
});
//Setting Current Activity Items
itemAdapter = new ItemAdapter(this, R.layout.list_item, temples);
templeListView.setAdapter(itemAdapter);
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Temple temple = dataSnapshot.getValue(Temple.class);
itemAdapter.add(temple);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
@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);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.search);
searchView = (SearchView) searchItem.getActionView();
assert searchManager != null;
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
itemAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.search) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_share) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String body = "108 Parshvanath Temples App \n\n" +
"Get it now on play store : http://play.google.com/store/apps/details?id=ga.vihanggarud.www.a108parshvnath";
intent.putExtra(Intent.EXTRA_TEXT,body);
startActivity(Intent.createChooser(intent, "Share via"));
}
else if (id == R.id.nav_store) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName())));
}
catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
}
else if (id == R.id.nav_about_us) {
Intent intent = new Intent(MainActivity.this, AboutUs.class);
startActivity(intent);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
这是我的适配器:
public class ItemAdapter extends ArrayAdapter<Temple> {
private Context context;
ItemAdapter(@NonNull Context context, int resource, @NonNull List<Temple> objects) {
super(context, resource, objects);
this.context = context;
}
public class ViewHolder {
ImageView templeImage;
TextView templeName;
}
@SuppressLint("InflateParams")
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder holder;
Temple temple = getItem(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
assert inflater != null;
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.templeName = convertView.findViewById(R.id.itemText);
holder.templeImage = convertView.findViewById(R.id.itemImage);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
assert temple != null;
holder.templeName.setText(temple.getTempleName());
Glide.with(holder.templeImage.getContext())
.load(temple.getTempleImageURI())
.into(holder.templeImage);
return convertView;
}
}
请在源代码中询问您是否还需要其他任何内容。
答案 0 :(得分:0)
您的adapter
必须实施Filterable
。下面是我从我自己的一个项目中获取的一些示例代码,您必须将其调整到您的数据模型以进行搜索,performFiltering方法迭代您的模型数组并将字段与约束进行比较。
public class MyAdapter extends RecyclerViewAdapter<MyModel, ViewHolder> implements Filterable {
private AppFilter appFilter;
...
@Override
public Filter getFilter() {
if (appFilter == null) {
appFilter = new MyFilter();
}
return appFilter;
}
private class MyFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<MyModel> tempList = new ArrayList<>();
// search content in friend list
for (MyModel myModel : myModels) {
if (myModel.field.toLowerCase().contains(constraint.toString().toLowerCase())) {
tempList.add(myModel);
}
}
filterResults.count = tempList.size();
filterResults.values = tempList;
} else {
filterResults.count = myModels.size();
filterResults.values = myModels;
}
return filterResults;
}
/**
* Notify about filtered list to ui
*
* @param constraint text
* @param results filtered result
*/
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredModels = (ArrayList<MyModel>) results.values;
notifyDataSetChanged();
}
}
}
根据@ anthony的评论,你必须包含可搜索的xml。
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/search">
</searchable>