我的问题很简单.如何清除视图中可能具有焦点的所有元素的焦点(如EditText – 或 – TextView,其textIsSelectable =“true”,并且在发生clearFocus事件时在其中选择文本).
为什么要问(如果我没有得到上面的通用答复):
我通过导航视图访问的片段很少.我的主要目标是在导航视图中打开抽屉时失去片段中元素的焦点.我知道可以为NavigationDrawer获取onDrawerSlide方法,并在我的MainActivity中设置它,以便在抽屉打开时,如果其中一个片段中的EditText打开,我调用hideSoftKeyboard代码以便关闭SoftKeyboard.
我的代码在抽屉打开时获取事件:(在MainActivity的onCreate()方法中)
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)
{
//Hide SoftKeyboard on Navigation Drawer Open
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
//Hide SoftKeyboard if it is open
hideSoftKeyboard();
//And Make any view having focus loose focus
//...
//ClearFocus for the whole view is done from here (for whichever Fragment is visible right now)
super.onDrawerSlide(drawerView, slideOffset);
}
};
public void hideSoftKeyboard() //Declared outside onCreate
{
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
在这里,我的hideSoftKeyboard()代码是通用的,并且可以关闭SoftKeyboard,无论目前可从MainActivity本身看到什么片段.类似地,我想清除所有EditTexts和TextView的焦点(因为复制/粘贴选项在打开时显示在抽屉的中间).
我知道我可以为每个片段编写调用onDrawerSlide函数的代码并单独清除每个元素的Focus,但我想知道是否可以使用通用解决方案,如果可以的话,该怎么做.
(如果有可能,可能会有很多含义,可能会在很多情况下有所帮助)