我有一个SearchView在导航抽屉上进行搜索,它隐藏了不符合搜索条件的元素,问题是隐藏的元素空间仍然存在。 如何删除这些空格?搜索之前:
SearchView onQueryTextListener的代码
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
//Add Listener to SearchView when the Drawer is opened by first time
@Override
public void onDrawerOpened(View view) {
if(searchView != null) return;
searchView = (SearchView) findViewById(R.id.dw_searchv);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
//Access to menu items container
NavigationMenuView containerOfMenuItems = ((NavigationMenuView)((NavigationView)drawer.getChildAt(1)).getChildAt(0));
int options = containerOfMenuItems.getChildCount();
//Iterate the container of menu items
for(int i=0; i<options; i++){
Object menuItem = containerOfMenuItems.getChildAt(i);
//Verify that the Child of container, is an menu item
if(menuItem.getClass() == NavigationMenuItemView.class) {
String titleOfMenuItem = ((AppCompatCheckedTextView)((NavigationMenuItemView) menuItem).getChildAt(0)).getText().toString();
if(titleOfMenuItem.toLowerCase().contains(s.toLowerCase()))
((NavigationMenuItemView) menuItem).setVisibility(View.VISIBLE);
else {
((NavigationMenuItemView) menuItem).setVisibility(View.INVISIBLE);
}
}
}
return false;
}
});
}
};
PD:View.GONE对我不起作用
答案 0 :(得分:0)
您必须添加一些代码以显示使用的内容 无论如何,您可以针对自己的情况执行以下操作
答案 1 :(得分:0)
请勿尝试修改构成NavigationView的视图,而应使用支持它的菜单:
// a field in your activity
private List<MenuItem> menuItems = new ArrayList<>();
在您的onCreate()方法中,保留对MenuItems初始列表的引用:
//...
NavigationView nav = findViewById(R.id.yourNavViewId);
navMenu = nav.getMenu();
for (int i = 0; i < navMenu.size(); i++) {
menuItems.add(navMenu.getItem(i));
}
然后在onQuery方法中使用该列表:
@Override
public boolean onQueryTextChange(String s) {
NavigationView nav = findViewById(R.id.yourNavViewId);
nav.getMenu().clear();
for (int i = 0; i < menuItems.size(); i++) {
MenuItem menuItem = menuItems.get(i);
if (menuItem.getTitle().toString().toLowerCase().contains(newText.toLowerCase()))
nav.getMenu().add(0, menuItem.getItemId(), 0, menuItem.getTitle());
}
}
答案 2 :(得分:0)
似乎迟到了。有解决方法/黑客。无需添加列表。 只需在代码上方添加这一行。当然可以。
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.candidates -> {
binding.navSideView.post {
navSideView.menu.findItem(R.id.candidateManagement).isVisible = !navSideView.menu.findItem(R.id.candidateManagement).isVisible
}
}
}
return true
}
您需要在更改可见性之前添加navigationview.post Runnable。它将更新菜单。它也适用于组。 :)