停止EditText在Activity启动时获得焦点

问题描述 投票:2646回答:49

我在Android中有一个Activity,有两个元素:

  1. EditText
  2. ListView

当我的Activity开始时,EditText立即有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我试过了:

EditText.setSelected(false);

没运气。当EditText开始时,我如何说服Activity不选择自己?

android listview android-edittext
49个回答
2428
投票

Luc和Mark的优秀答案却缺少一个好的代码示例。像下面的例子一样将标签android:focusableInTouchMode="true"添加到<LinearLayout>将解决问题。

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:focusable="true" 
    android:focusableInTouchMode="true"
    android:layout_width="0px" 
    android:layout_height="0px"/>

<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:nextFocusUp="@id/autotext" 
    android:nextFocusLeft="@id/autotext"/>

44
投票

最晚但最简单的答案,只需在XML的父布局中添加它。

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

如果它有帮助你Upvote!快乐编码:)


42
投票

这些解决方案都不适合我。我修复自动对焦的方式是:

<activity android:name=".android.InviteFriendsActivity" android:windowSoftInputMode="adjustPan">
    <intent-filter >
    </intent-filter>
</activity>

39
投票

简单的解决方案:在AndroidManifest中使用Activity标签

android:windowSoftInputMode="stateAlwaysHidden"

34
投票

您可以在TextView的第一个layout上将“可聚焦”和“可聚焦在触摸模式”设置为真值。通过这种方式,当活动开始时,TextView将被聚焦,但由于其性质,你将看不到任何聚焦在屏幕上,当然,将没有键盘显示...


33
投票

以下在Manifest为我工作。写,

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>

28
投票

我需要以编程方式清除所有字段的焦点。我刚刚在主要布局定义中添加了以下两个语句。

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);

而已。马上解决了我的问题。谢谢,西尔弗,指出我正确的方向。


26
投票

android:windowSoftInputMode="stateAlwaysHidden"文件的activity标记中添加Manifest.xml

Source


22
投票

如果您对自己的活动有另一种观点,例如ListView,您还可以:

ListView.requestFocus(); 

在你的onResume()editText抓住焦点。

我知道这个问题已得到解答,但只是提供了一个对我有用的替代解决方案:)


21
投票

onCreate方法中添加以下内容:

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

20
投票

在第一个可编辑字段之前尝试此操作:

<TextView  
        android:id="@+id/dummyfocus" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="@string/foo"
        />

----

findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
findViewById(R.id.dummyfocus).requestFocus();

1642
投票

实际问题是你根本不希望它有焦点吗?或者你不希望它通过聚焦EditText来显示虚拟键盘?我并没有真正看到EditText关注启动的问题,但是当用户没有明确要求关注EditText(并且因此打开键盘)时,打开softInput窗口肯定是个问题。

如果是虚拟键盘的问题,请参阅AndroidManifest.xml <activity> element文档。

android:windowSoftInputMode="stateHidden" - 在进入活动时始终隐藏它。

android:windowSoftInputMode="stateUnchanged" - 不要更改它(例如,如果它尚未显示,则不显示,但如果在进入活动时打开,则将其保持打开状态)。


17
投票

由于我不喜欢用与功能相关的东西污染XML,我创建了这个方法,“透明地”从第一个可聚焦视图中窃取焦点,然后确保在必要时自行移除!

public static View preventInitialFocus(final Activity activity)
{
    final ViewGroup content = (ViewGroup)activity.findViewById(android.R.id.content);
    final View root = content.getChildAt(0);
    if (root == null) return null;
    final View focusDummy = new View(activity);
    final View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean b)
        {
            view.setOnFocusChangeListener(null);
            content.removeView(focusDummy);
        }
    };
    focusDummy.setFocusable(true);
    focusDummy.setFocusableInTouchMode(true);
    content.addView(focusDummy, 0, new LinearLayout.LayoutParams(0, 0));
    if (root instanceof ViewGroup)
    {
        final ViewGroup _root = (ViewGroup)root;
        for (int i = 1, children = _root.getChildCount(); i < children; i++)
        {
            final View child = _root.getChildAt(i);
            if (child.isFocusable() || child.isFocusableInTouchMode())
            {
                child.setOnFocusChangeListener(onFocusChangeListener);
                break;
            }
        }
    }
    else if (root.isFocusable() || root.isFocusableInTouchMode())
        root.setOnFocusChangeListener(onFocusChangeListener);

    return focusDummy;
}

15
投票

晚了,但也许有帮助。在布局顶部创建一个虚拟EditText,然后在myDummyEditText.requestFocus()中调用onCreate()

<EditText android:id="@+id/dummyEditTextFocus" 
android:layout_width="0px"
android:layout_height="0px" />

这看起来像我期望的那样。不需要处理配置更改等。我需要这个用于具有冗长TextView(指令)的Activity。


13
投票

是的,我做了同样的事情 - 创建一个'虚拟'线性布局,获得初始焦点。此外,我设置了“下一个”焦点ID,因此在滚动一次后用户无法再对焦:

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());

dummy.setNextFocusUpId(et.getId());

et.setNextFocusUpId(et.getId());

很多工作只是为了摆脱对视图的关注..

谢谢


12
投票

对我来说,适用于所有设备的是:

    <!-- fake first focusable view, to allow stealing the focus to itself when clearing the focus from others -->

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

在有问题的焦点视图之前把它作为一个视图,就是这样。


12
投票

在父布局中写下这一行......

 android:focusableInTouchMode="true"

10
投票

这是最完美,最简单的解决方案。我总是在我的应用程序中使用它。

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

9
投票

我做的最简单的事情是将焦点放在onCreate的另一个视图上:

    myView.setFocusableInTouchMode(true);
    myView.requestFocus();

这使得软键盘停止运行,EditText中没有光标闪烁。


8
投票

将此代码写入Manifest中的Activity文件中,您不想打开键盘。

android:windowSoftInputMode="stateHidden"

清单文件:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.projectt"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="24" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
         <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            **android:windowSoftInputMode="stateHidden"**
            android:label="@string/app_name" >
        </activity>

    </application>

</manifest>

8
投票
<TextView
    android:id="@+id/TextView01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    style="@android:style/Widget.EditText"/>

7
投票

在Activity的onCreate中,只需在EditText元素上添加使用clearFocus()即可。例如,

edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();

如果你想将焦点转移到另一个元素,请使用requestFocus()。例如,

button = (Button) findViewById(R.id.button);
button.requestFocus();

1101
投票

存在更简单的解决方案。在父布局中设置这些属性:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >

现在,当活动开始时,此主要布局将默认获得焦点。

此外,我们可以通过再次将焦点放在主布局上,在运行时从子视图中删除焦点(例如,在完成子编辑之后),如下所示:

findViewById(R.id.mainLayout).requestFocus();

来自Guillaume Perrot的好评:

android:descendantFocusability="beforeDescendants"似乎是默认值(整数值为0)。它只是通过添加android:focusableInTouchMode="true"工作。

真的,我们可以看到beforeDescendantsViewGroup.initViewGroup()方法(Android 2.2.2)中设置为默认值。但不等于0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

感谢Guillaume。


6
投票

您可以通过创建布局宽度和高度设置为EditText的虚拟0dp来实现此目的,并请求焦点到该视图。在xml布局中添加以下代码段:

<EditText
    android:id="@+id/editText0"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/dummy"
    android:ems="10" 
    >
     <requestFocus />
    </EditText>

415
投票

我发现的唯一解决方案是:

  • 创建一个LinearLayout(我不知道其他类型的布局是否有效)
  • 设置属性android:focusable="true"android:focusableInTouchMode="true"

并且EditText在开始活动后不会得到关注


78
投票

问题似乎来自于我只能在布局的XML form中看到的属性。

确保在EditText XML标记内的声明末尾删除此行:

<requestFocus />

这应该是这样的:

<EditText
   android:id="@+id/emailField"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textEmailAddress">

   //<requestFocus /> /* <-- without this line */
</EditText>

70
投票

使用其他海报提供的信息,我使用了以下解决方案:

在布局XML中

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:id="@+id/linearLayout_focus"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"/>

<!-- AUTOCOMPLETE -->
<AutoCompleteTextView
    android:id="@+id/autocomplete"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
    android:inputType="textNoSuggestions|textVisiblePassword"/>

在onCreate()

private AutoCompleteTextView mAutoCompleteTextView;
private LinearLayout mLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    //get references to UI components
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_focus);
}

最后,在onResume()

@Override
protected void onResume() {
    super.onResume();

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}

68
投票

试试clearFocus()而不是setSelected(false)。 Android中的每个视图都具有可聚焦性和可选择性,我认为您只想清除焦点。


66
投票

以下内容将阻止edittext在创建时获得焦点,但在触摸时抓住它。

<EditText
    android:id="@+id/et_bonus_custom"
    android:focusable="false" />

所以你在xml中将focusable设置为false,但关键是在java中,你添加了以下监听器:

etBonus.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        return false;
    }
});

因为您返回false,即不消耗该事件,所以聚焦行为将正常进行。


56
投票

我曾单独尝试了几个答案,但重点仍然是EditText。我只是通过使用以下两个解决方案来设法解决它。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLayout"
  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true" >

(参考来自Silver https://stackoverflow.com/a/8639921/15695

并删除

 <requestFocus />

在EditText

(来自floydaddict https://stackoverflow.com/a/9681809的参考)

© www.soinside.com 2019 - 2024. All rights reserved.