Android: Force EditText to remove focus? [duplicat

2019-01-03 20:32发布

This question already has an answer here:

I would like to be able to remove the focus from the EditText. For example if the Keyboard appears, and the user hides it with the back button, I would like the focus and the cursor to disappear. How can it be done?

19条回答
啃猪蹄的小仙女
2楼-- · 2019-01-03 21:03

try to use this one on your view it worked for me:

<View
    android:id="@+id/fucused"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"/>
查看更多
闹够了就滚
3楼-- · 2019-01-03 21:05

You can avoid any focus on your elements by setting the attribute android:descendantFocusability of the parent element.

Here is an example:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search__scroller"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ScrollView>

Here, the attribute android:descendantFocusability set to "blocksDescendants" is blocking the focus on the child elements.

You can find more info here.

查看更多
一夜七次
4楼-- · 2019-01-03 21:10

You can make cursor and focus disappear by

edittext.clearFocus();

But detect when the key board hide is a hard work.

查看更多
在下西门庆
5楼-- · 2019-01-03 21:11
editText.setFocusableInTouchMode(true)

The EditText will be able to get the focus when the user touch it. When the main layout (activity, dialog, etc.) becomes visible the EditText doesn't automatically get the focus even though it is the first view in the layout.

查看更多
爷的心禁止访问
6楼-- · 2019-01-03 21:11
check your xml file
 <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp" >

            **<requestFocus />**
 </EditText>


//Remove  **<requestFocus />** from xml
查看更多
smile是对你的礼貌
7楼-- · 2019-01-03 21:13

You can also include android:windowSoftInputMode="stateAlwaysHidden" in your manifest action section.

This is equivalent to :

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

but in XML way.

FYI, you can also hide the keyboard with codes:

// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);
查看更多
登录 后发表回答