Android取消EditText自动聚焦、自动弹出输入法的方法

当跳转到带有EditText的界面后,App会自动弹出输入法,严重影响了用户体验。因此,我们有时候需要取消EditText的默认聚焦。

方法一:
在EditText的父控件中加上这两行代码:

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

例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Method1Activity"
    android:orientation="vertical"
    android:focusable="true"				//
    android:focusableInTouchMode="true">	//

    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="0123456789"
        android:textSize="20sp"/>
</LinearLayout>

方法二:
使用代码使外层组件获取焦点,代码如下:

View.setFocusable(true);
View.setFocusableInTouchMode(true);
View.requestFocus();//有时需要添加,谨慎起见建议全部都加

示例:

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ll"		//
    tools:context=".Method2Activity"
    android:orientation="vertical">

    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="0123456789"
        android:textSize="20sp"/>
</LinearLayout>

代码:
		LinearLayout ll = findViewById(R.id.ll);
        ll.setFocusable(true);
        ll.setFocusableInTouchMode(true);
        ll.requestFocus();

方法三:
将该窗口下的输入法隐藏起来,代码如下(仅隐藏输入法,需要在setContentView()前调用):

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

示例:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow()
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.activity_method3);
    }

方法四:
在AndroidManifest相应的Activity中添加如下代码(仅隐藏输入法):

android:configChanges="keyboardHidden|orientation"
android:windowSoftInputMode="adjustResize|stateHidden"

示例:

<activity android:name=".Method4Activity"
            android:configChanges="keyboardHidden|orientation"
            android:windowSoftInputMode="adjustResize|stateHidden"/>


源代码下载:Github下载链接

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值