[英]Hide virtual keyboard on EditText focus lost
我知道這個問題已經被問過百萬遍了,但是我無法為我的特定問題找到直接的解決方案。
在我的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"
/>
現在添加TouchListener
這個imageView
在您的活動。
嘗試這個
<Your EditView>.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
If(!hasfocus)
hideSoftKeyboard()
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.