有的小伙伴在Android项目开发中可能遇到了在点击Home键时关闭系统软键盘的问题。对于这个问题,可以通过注册广播的形式解决。现分享一段代码,仅供参考。
public class HideSoftInputActivity extends Activity { private EditText mSearchInput; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact_search); mSearchInput = (EditText) findViewById(R.id.et_search_select_input); registerReceiver(mHomeKeyEventReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); showSoftInput(); } /** * 隐藏软件输入(隐藏输入键盘) */ private void hideSoftInput() { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mSearchInput.getWindowToken(), 0); } /** * 强制开启软键盘 */ private void showSoftInput() { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { mSearchInput.setFocusable(true); mSearchInput.setFocusableInTouchMode(true); InputMethodManager inputManager = (InputMethodManager) mSearchInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(mSearchInput, InputMethodManager.SHOW_FORCED); } }, 300); } /** * 监听home键,关闭键盘 */ private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() { String SYSTEM_REASON = "reason"; String SYSTEM_HOME_KEY = "homekey"; String SYSTEM_HOME_KEY_LONG = "recentapps"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_REASON); if (TextUtils.equals(reason, SYSTEM_HOME_KEY) || TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) { hideSoftInput(); } } } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mHomeKeyEventReceiver); } }
本文介绍了在Android开发中如何实现点击Home键时关闭系统软键盘的方法,通过注册广播接收器来解决这一问题。提供了一段参考代码。

1306

被折叠的 条评论
为什么被折叠?



