我知道这个问题已被问过数百万次,但我无法找到针对我的具体问题的直接解决方案。
在我的 SearchActivity 中,有一个 EditText
和一个 ListView
。
我希望即使用户触摸除 EditText 之外的任何地方,键盘也应该关闭。
我所做的是在 ListView 上设置一个 TouchListener
,每当触摸它时,键盘就会关闭。
但是它产生了一个问题,当我触摸 ListView 的任何元素时,键盘会隐藏,但列表的元素变得不可见。
请提出比这更好的方法。
我的代码:
public class SearchActivity extends Activity implements OnTouchListener {
RelativeLayout rlSearchLayout;
EditText etSearchBar;
ListView lvSearchResult;
private static String searchText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
setTitle("SearchActivity.java");
etSearchBar = (EditText) findViewById(R.id.etSearchBar);
lvSearchResult = (ListView) findViewById(R.id.lvSearchResult);
searchText = etSearchBar.getText().toString();
lvSearchResult.setOnTouchListener(this);
String[] objects = { "One", "two" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, objects);
lvSearchResult.setAdapter(adapter);
}
@Override
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etSearchBar.getWindowToken(), 0);
return false;
}
}
最佳答案
将其添加到您的布局文件中。
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#80000000"
/>
现在在您的 Activity 中为此 imageView
添加一个 TouchListener
。
关于java - 隐藏 EditText 上的虚拟键盘焦点丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11664881/