android edittext remove focus after clicking a but

2020-05-20 05:15发布

I have an Activity with an EditText and a Button. When the User clicks on the EditText, the keyboard is shown and he can type in some Text - fine. But when the user clicks on the Button I want the EditText to be no more in focus i.e. the keyboard hides til the user clicks again on the EditText.

What can I do to 'hide the focus' of the EditText, after the Button is clicked. Some Code I can add in the OnClick Method of the Button to do that?

EDIT:

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <EditText 
        android:id="@+id/edt_SearchDest"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.8"
        android:textSize="18sp"
        android:hint="Enter your look-up here.." />

    <Button
        android:id="@+id/btn_SearchDest"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:text="Search" />

</LinearLayout>

Best Regards

9条回答
Emotional °昔
2楼-- · 2020-05-20 05:38
private void hideDefaultKeyboard() {
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);//u have got lot of methods here
}

EDIT:

LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
查看更多
劫难
3楼-- · 2020-05-20 05:39

One workaround is to create a fake view to transfer focus to when you clearFocus in your edittext:

<EditText
        android:id="@+id/edt_thief"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:focusable="true"
        android:focusableInTouchMode="true"

Note that this view is invisible so it doesn't require any space in the layout.

In the control class, you can add a method like the following to trigger this focus transfer:

public void clearFocus(){
        yourEdittext.clearFocus();
        edtThief.requestFocus();
    }

You can then minimize the keyboard once edtThief has focus:

 public static void hideKeyboard(final View view) {
    InputMethodManager imm = (InputMethodManager) view.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
查看更多
SAY GOODBYE
4楼-- · 2020-05-20 05:39

How i solved it.

// xml file
<LinearLayout
...
android:id="@+id/linear_layout"
android:focusableInTouchMode="true"> // 1. make this focusableInTouchMode...
</LinearLayout>

// Activity file
private LinearLayout mLinearLayout; // 2. parent layout element
private Button mButton;

mLinearLayout = findViewById(R.id.linear_layout);
mButton = findViewById(R.id.button);

  mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLinearLayout.requestFocus(); // 3. request focus

            }
        });

I hope this helps you :)

查看更多
登录 后发表回答