我在我的项目中使用MVP模式,并且试图从视图访问MainActivity菜单中的SearchView。该视图是MainActivity内的FrameLayout,其中有一个RecyclerView,当我单击一行时,我想折叠SearchView,但我不知道如何正确执行。我知道如何从MainActivity折叠它,但不从View折叠它。
在这里我在MainActivity中创建菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_user_list, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
mUserView.mUsersAdapter.getFilter().filter(s);
return false;
}
});
searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
mUserView.mScrollListener.searchViewFiltering = true;
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mUserView.mScrollListener.searchViewFiltering = false;
return true;
}
});
return true;
}
menumain.xml
<item android:id="@+id/action_search"
android:icon="@drawable/ic_search_24dp"
android:title="@string/search_menu"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
以及我要在其中调用SearchView的RecyclerView View Holder中的OnClick方法,该方法放置在UsersView.java(FrameLayout)中
private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
//Here I want to collapse the SearchView
User mUser = (User) view.getTag();
Context context = view.getContext();
Intent intent = new Intent(context, UserDetailActivity.class);
intent.putExtra("userObj", mUser);
context.startActivity(intent);
}
};