所以我在MainActivity中有一个导航抽屉,当点击可扩展列表视图的子项时,内容以片段形式显示。 在片段内部我有一个菜单图标,当点击时,正在显示搜索文本框和软输入键盘。但如果有人按下切换按钮打开导航抽屉,则软输入键盘不会消失。我试过这个方法:
第一种方法:从onDrawerClosed关闭MainActivity键盘,使用此代码,没有任何反应:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
第二种方法:从方法onOptionsItemSelected(MenuItem项)关闭MainActivity键盘,获取项目ID并编写与之前相同的代码:android.R.id.home,什么都没发生
第三种方法:作为前一种方法,但在Fragment编写上述代码中,没有任何反应:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
软输入键盘从片段打开,所以我不能使用上面代码中的代码,因为ed_search是在片段中声明的。
这是主要活动的代码:
public class MainActivity extends AppCompatActivity {
private static DrawerLayout mDrawerLayout;
private static ExpandableListView mExpandableListView;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private Toolbar mToolbar;
//nav drawer Title
private CharSequence mDrawerTitle;
//used to store app titles
private String mTitles;
//slide menu items
private String[] navMenuItems;
private String[] navSubMenuItems;
private TypedArray navMenuIcons;
private String[] navMenuLinks;
private List<NavDrawerItem> groupList;
private List<NavDrawerItem> childList;
private Map<NavDrawerItem, List<NavDrawerItem>> mapList;
private ExpandableListViewAdapter mAdapter;
//Fragment
private FragmentManager lFragmentManager;
private Fragment lFragment;
private static final NavDrawerItem firstItem = new NavDrawerItem("Latest",
"http://thegadgetflow.com/?feed=full_feed&paged=%d");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Toolbar customization
*/
mToolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mTitles = firstItem.getTitle(); //setting the title of the first item
getSupportActionBar().setTitle(" Home");// changing the title of the action bar with the name of the item
/**
* Home screen
*/
lFragmentManager = getFragmentManager();
lFragment = lFragmentManager.findFragmentById(R.id.frame_container);
lFragment = new FragmentListItemHome();
Bundle mBundle = new Bundle();
mBundle.putSerializable("Item", firstItem);
lFragment.setArguments(mBundle);
//To the fragment
lFragmentManager.beginTransaction().replace(R.id.frame_container ,lFragment ).commit();
//navigation Drawer
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
//populate the expandable List view
createGroupList();
CreateChildList();
//put a reference to the expandable List view
mExpandableListView = (ExpandableListView)findViewById(R.id.list_slideMenu);
/**
* changing the groupIndicator from left to right
*/
mExpandableListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
mExpandableListView.removeOnLayoutChangeListener(this);
//getting the width of the Expandable List view
int width = mExpandableListView.getWidth();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
mExpandableListView.setIndicatorBounds(width - getDipsFromPixel(35), width
- getDipsFromPixel(5));
} else {
mExpandableListView.setIndicatorBoundsRelative(width - getDipsFromPixel(35), width
- getDipsFromPixel(5));
}
}
});
// A new adapter
mAdapter = new ExpandableListViewAdapter(this, mapList, groupList);
//setting the adapter
mExpandableListView.setAdapter(mAdapter);
/**
* when a child of the Expandable list view is clicked
*/
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
final NavDrawerItem lItem = (NavDrawerItem) mAdapter.getChild(
groupPosition, childPosition);
mTitles = lItem.getTitle();
/**
* A new fragment
*/
boolean close = openListFragment(lItem);
//closing the navigation drawer
if (close) {
mDrawerLayout.closeDrawer(mExpandableListView);
//changing the title of the action bar with the title of the ChildItem
mToolbar.setTitle(" " + lItem.getTitle());
}
return true;
}
});
/**
* toggling the sliding menu
*/
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
R.string.app_name, R.string.app_name) {
@Override
public void onDrawerClosed(View drawerView) {
mToolbar.setTitle(" " + mTitles);
invalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
mToolbar.setTitle(" Sidebar");
invalidateOptionsMenu();
}
};
mActionBarDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_drawer);
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
//changing the ScrimColor
mDrawerLayout.setScrimColor(getResources().getColor(R.color.ColorPrimary));
CommonUtils.setContext(getApplicationContext());
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mExpandableListView);
//hiding the menu items of the action bar if the navigation drawer is open
if(mDrawerLayout!=null && drawerOpen)
menu.clear();
return super.onPrepareOptionsMenu(menu);
}
@Override
public void setTitle(CharSequence title) {
mTitles = (String)title;
mToolbar.setTitle(" Latest");
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurSationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mActionBarDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.findItem(R.id.action_search).setVisible(false);
menu.findItem(R.id.action_share).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
//not working
switch (item.getItemId()){
case android.R.id.home:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* changing the title inside a fragment
* @param title
*/
public void setActionBarTitle(String title) {
mToolbar.setTitle(title);
}
@Override
protected void onResume()
{
CommonUtils.resetBackButton();
super.onResume();
}
这是片段中的代码:
public class FragmentListItemHome extends Fragment {
RelativeLayout rl_row_progress_bar;
LinearLayout ln_search;
EditText ed_search;
private RecyclerView mRecyclerView;
private ArrayList<GadgetItem> mList;
private AdapterListItemHome mAdapter;
private GridLayoutManager mLayoutManager;
private String mUrl;
private String mTitleGadget;
private View v;
private ImageButton mImageButton;
int loadedPage;
NavDrawerItem mData;
String searchText;
boolean isSearchMode;
int maxScrolledPage = 0;
boolean preloadingCancelled;
int spanSize = 2;
int pauseCounter = 0;
InputMethodManager inputMethod;
//paging
Map<Integer, Boolean> _loadingPages = new HashMap<Integer, Boolean>();
Map<Integer, Integer> _pageIndexes = new HashMap<Integer, Integer>();
private Toolbar mToolbar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadedPage = 1;
/**
* Toolbar customization
*/
savedInstanceState = getArguments();
if (savedInstanceState != null) {
mData = (NavDrawerItem) savedInstanceState.getSerializable("Item");
}
isSearchMode = false;
//for the search button in the action bar
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent , Bundle savedInstanceState) {
if(parent == null)
return null;
if(v != null)
return v;
//initialize the view v
v = inflater.inflate(R.layout.fragment_list_item_home, parent , false);
//initialization Recycler view
v.findViewById(R.id.rl_row_progress_bar_home); //the progress bar
//search items
mImageButton =(ImageButton)v.findViewById(R.id.anchor_home); //anchor
ln_search = (LinearLayout) v.findViewById(R.id.ln_search_home); // the layout for searching
ed_search = (EditText) v.findViewById(R.id.ed_search_home); // the text box for searching
ed_search.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
/**
* Overriding the soft keyboard for the search text box
*/
ed_search.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int Keycode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (Keycode == KeyEvent.KEYCODE_SEARCH) || (Keycode == KeyEvent.KEYCODE_ENTER)) {
inputMethod = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethod.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
String key = ed_search.getText().toString();
if (key != null && !key.isEmpty()) {
searchData(key);
}
}
return false;
}
});
/**
* Scrolling
*/
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
//getting the last visible position of the list
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//when scrolling hide keyboard and search box
ln_search.setVisibility(View.GONE);
showKeyboard(false);
int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
if (newState == recyclerView.SCROLL_STATE_IDLE) {
//Log.d("bill",String.valueOf(lastPosition));
int onScrollingPage = getOnScrollingPage(firstVisibleItems);
if (maxScrolledPage <= onScrollingPage)
maxScrolledPage = onScrollingPage;
//int myPosition = layoutManager.getPosition();
//hiding the anchor when the lastPosition is 0
if (firstVisibleItems == 0)
mImageButton.setVisibility(View.GONE);
loadPage(onScrollingPage + 1);
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
if (mLayoutManager != null && mLayoutManager.getItemCount() < 5) {
return;
} else {
changeFooterState(true);
}
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int pastVisiblesItems = firstVisibleItems;
// Log.d("bill","visibleItemCount: "+String.valueOf(visibleItemCount)+
// "totalItemCount: "+String.valueOf(totalItemCount)+"firstVisibleItem: "+String.valueOf(pastVisiblesItems));
if (pastVisiblesItems + visibleItemCount == totalItemCount && (mList != null && totalItemCount == mList.size())
&& totalItemCount != 0) {
changeFooterState(false);
} else {
changeFooterState(true);
}
}
});
}
/**
* searching
*/
public void searchData(String searchKey) {
loadedPage = 1;
_loadingPages.clear(); // clear the hash map
_pageIndexes.clear();
isSearchMode = true;
this.searchText = searchKey;
if(mList != null && mAdapter != null) {
mList.clear(); // clear the list
mAdapter.notifyDataSetChanged();
}
// Set title bar
((MainActivity) getActivity())
.setActionBarTitle(searchKey);
CommonUtils.showDialog(getActivity(), "Searching...", false);
getGadget(searchKey);
}
/**
*
* @param menu
* @param inflater
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//the button search is setting to visible
menu.findItem(R.id.action_search).setVisible(true);
menu.findItem(R.id.action_share).setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_search:
isSearchMode = true;
//Log.d("billy","inside action_search");
rightHeaderButtonClick();
return true;
//how working
case R.id.action_share:
return false;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* showing the text box
*/
public void rightHeaderButtonClick() {
if (ln_search.isShown()) {
ln_search.setVisibility(View.GONE);
showKeyboard(false);
} else {
ln_search.setVisibility(View.VISIBLE);
ed_search.requestFocus();
showKeyboard(true);
//Log.d("bill", "rightHeaderButtonClick - open ln_search");
}
}
/**
* showing the keyboard
* @param isShow
*/
public void showKeyboard(boolean isShow) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE);
if (isShow) {
// show keyboard
imm.showSoftInput(ed_search, 0);
} else {
// hide keyboard
imm.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
}
}
提前致谢!
答案 0 :(得分:4)
使用此
public static void showKeyboard(Activity pActivity, View pView) {
if (pView == null) {
pView = pActivity.getWindow().getCurrentFocus();
} else {
/**
* For {@link EditText}, a call to {@link View#requestFocus()} will
* open the keyboard as per inputType set for {@link EditText}
*/
pView.requestFocus();
}
if (pView != null) {
InputMethodManager imm = (InputMethodManager) pActivity
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(pView, InputMethodManager.SHOW_FORCED);
}
}
}
public static void hideKeyboard(View pView, Activity pActivity) {
if (pView == null) {
pView = pActivity.getWindow().getCurrentFocus();
}
if (pView != null) {
InputMethodManager imm = (InputMethodManager) pActivity
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(pView.getWindowToken(), 0);
}
}
}
答案 1 :(得分:1)
我有类似的情况,我在导航抽屉的子片段中搜索。
现在正在搜索键盘会弹出,当我想再次点击导航抽屉时,键盘不会隐藏,所以我把上面的2个解决方案混合起来并想出了这个。
<div id="time">
<span id="hour">hh</span>:<span id="min">mm</span>:<span id="sec">ss</span>
</div>
setInterval(update, 1000);
function update() {
var date = new Date()
var hours = date.getHours()
if (hours < 10) hours = '0'+hours
document.getElementById('hour').innerHTML = hours
var minutes = date.getMinutes()
if (minutes < 10) minutes = '0'+minutes
document.getElementById('min').innerHTML = minutes
var seconds = date.getSeconds()
if (seconds < 10) seconds = '0'+seconds
document.getElementById('sec').innerHTML = seconds
}
并猜猜这是有效的!谢谢你的帮助!