【问题标题】:Clear edittext focus and hide keyboard when button is pressed按下按钮时清除edittext焦点并隐藏键盘
【发布时间】:2013-07-03 17:19:05
【问题描述】:

我正在制作一个带有 edittext 和一个按钮的应用程序。当我在 edittext 中输入内容然后单击按钮时,我希望键盘和焦点在 edittext 上消失,但我似乎做不到。

我在 XML 中插入了这两行代码:

android:focusable="true"
android:focusableInTouchMode="true"

我也尝试在按钮点击方法中添加这个:

edittext.clearFocus();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

而且它不起作用,在我按下按钮后,键盘仍然存在并且edittext仍然具有焦点。

【问题讨论】:

    标签: java android eclipse focus android-edittext


    【解决方案1】:

    要隐藏键盘调用这个:

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
    

    您还可以检查此解决方案: https://stackoverflow.com/a/15587937/786337

    【讨论】:

      【解决方案2】:
      InputMethodManager inputManager = (InputMethodManager)
                                        getSystemService(Context.INPUT_METHOD_SERVICE); 
      
      inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                           InputMethodManager.HIDE_NOT_ALWAYS);
      editText.setText("");
      

      在您的按钮 onclick 事件中添加以下内容

      你需要import android.view.inputmethod.InputMethodManager;

      当您单击按钮时,键盘会隐藏和清除文本。

      【讨论】:

        【解决方案3】:

        另一种解决方案是,创建一个虚拟布局

        <!-- Dummy item for focus at startup -->
        <LinearLayout
            android:id="@+id/dummy_id"
            android:orientation="vertical"
            android:layout_width="0px"
            android:layout_height="0px"
            android:focusable="true"
            android:focusableInTouchMode="true" />
        

        并将焦点设置在您的onButtonClickFunction

        ((LinearLayout) findViewById(R.id.dummy_id)).requestFocus();
        

        【讨论】:

          【解决方案4】:

          首先你必须禁用键盘:

          void hideKeyboard(Activity activity) { View view = activity.getCurrentFocus(); InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); assert manager != null && view != null; manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }

          第二个清晰的视图(布局,EditText...)焦点:

          view.clearFocus

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-31
            • 2011-03-07
            • 2020-04-21
            • 1970-01-01
            • 2017-01-13
            • 1970-01-01
            • 2014-04-24
            • 2012-07-05
            相关资源
            最近更新 更多