android的EditText默认不自动获取焦点

文章讨论了Android开发中处理EditText自动获取焦点的常见不靠谱方案,并推荐了一种通过增加一个大小为0的隐藏EditText来抢占焦点的更有效方法。
摘要由CSDN通过智能技术生成

网上搜了很多方案,结果都不靠谱,以下是比较常见的不靠谱方案

1、在EditText前面放置一个隐藏的线性布局:

<LinearLayout
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"
    />

2、在manifest中对activity进行配置

<activity ...  android:windowSoftInputMode="stateAlwaysHidden|adjustResize"  />

3、在EditText的父级控件中设置

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"      
    android:focusableInTouchMode="true"
    android:orientation="vertical">

    <androidx.appcompat.widget.AppCompatEditText
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"
         />

</LinearLayout>

下面是比较靠谱的方案:

在EditText面前,增加一个大小的0的EditText,目的是让它先抢走焦点,因为大小为0,所以用户也看不见,可以完美解决问题
 

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.appcompat.widget.AppCompatEditText
            android:layout_width="0dp"
            android:layout_height="0dp" />

        <androidx.appcompat.widget.AppCompatEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

EditText默认获取焦点并弹出软键盘,在Android开发中非常常见和实用。当我们在布局文件中使用EditText控件时,默认情况下,该控件会自动获取焦点并弹出软键盘。 这种默认行为可以方便用户直接对EditText进行输入操作,提高用户的交互体验。当用户点击EditText或切换到包含EditText的布局时,EditText自动获得焦点,这样用户可以直接进行输入操作。 在代码中,我们可以通过设置android:focusable属性为true来保证EditText默认获取焦点。同时,还可以设置android:focusableInTouchMode属性为true,确保用户触摸到屏幕上的EditText时,它会获取焦点并弹出软键盘。 例如,在布局文件中可以这样设置: <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true" android:focusableInTouchMode="true" /> 这样,当布局加载完成后,EditText自动获取焦点,用户可以直接对其进行输入操作。 需要注意的是,如果你希望EditText不再获取焦点和弹出软键盘,则可以将android:focusable和android:focusableInTouchMode属性设置为false。 尽管EditText默认获取焦点和弹出软键盘在很多情况下非常方便,但有些场景可能不适用,比如登录界面中的密码框,我们可能更愿意让用户手动点击密码框来输入密码,而不是自动弹出软键盘。 总之,EditText默认获取焦点并弹出软键盘是一个很方便的功能,可以提高用户的交互体验,但在一些特殊场景中需要谨慎使用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值