当活动在 Android 中开始时,如何阻止 EditText 获得焦点?

How to stop EditText from gaining focus when an activity starts in Android?

提问人:Mark 提问时间:10/12/2009 最后编辑:Ramesh RMark 更新时间:9/28/2022 访问量:824450

问:

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

  1. EditText
  2. ListView

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

EditText.setSelected(false);
EditText.setFocusable(false);

没有运气。我怎样才能说服它在开始时不选择自己?EditTextActivity

Android 列表视图 android-activity android-edittext 焦点

评论


答:

85赞 Eric Mill 10/13/2009 #1

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

评论

1赞 Mark 10/13/2009
这听起来很有希望,但是在活动生命周期的哪个阶段应该调用它呢?如果我在 onCreate() 中调用它,EditText 仍然具有焦点。它应该在 onResume() 或其他位置调用吗?谢谢!
9赞 teedyay 10/15/2010
我将接受的答案与这个答案结合起来。我打电话给活动。这确保了 EditText 在手机旋转时不会保持焦点。myEditText.clearFocus(); myDummyLinearLayout.requestFocus();onResume
455赞 Luc 10/23/2009 #2

我找到的唯一解决方案是:

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

而且在开始活动后不会得到焦点EditText

评论

0赞 iamnaran 9/26/2021
谢谢,也适用于其他布局。在约束布局上进行了测试。
0赞 Konstantin Konopko 5/5/2023
您还可以将根布局设置为可聚焦
17赞 mark 10/23/2009 #3

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

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());
 
dummy.setNextFocusUpId(et.getId());
 
et.setNextFocusUpId(et.getId());

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

谢谢

2845赞 Morgan Christiansson 11/2/2009 #4

将标签和添加到父布局(例如 或 ) (如以下示例所示)将解决问题。android:focusableInTouchMode="true"android:focusable="true"LinearLayoutConstraintLayout

<!-- 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"/>

评论

757赞 Muhammad Babar 3/21/2014
布局设置为 !android:focusableInTouchMode="true"
0赞 greja 5/17/2021
@MuhammadBabar android:focusableInTouchMode=“true”在模拟器中创建缩放视图
0赞 Arjun Verma 6/1/2021
就我而言,添加文本视图也可以
0赞 D_K 3/8/2022
如果 SO 允许我多次对问题投赞成票,那么我将对这个答案投两次赞成票。谢谢兄弟
1739赞 Joe 4/10/2010 #5

实际问题是你根本不想让它集中注意力吗?或者您不希望它显示虚拟键盘,因为专注于 ?我真的没有看到将焦点放在开始上的问题,但是当用户没有明确请求将焦点放在(并因此打开键盘)时,打开 softInput 窗口绝对是一个问题。EditTextEditTextEditText

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

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

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

评论

27赞 martyglaubitz 5/20/2014
但光标仍然位于布局中的第一个 EditText 中 - 即使未显示键盘
45赞 Joe 7/9/2014
@Anderson:答案没有任何暗示会阻止焦点。它实际上清楚地表明,这就是您防止软件键盘 IME 在焦点上自动打开的方式;因为更大的担忧更有可能是软键盘意外弹出,而不是焦点本身。如果你的问题与实际的焦点有关,那么就使用别人的答案。EditTextEditText
0赞 GHH 9/26/2023
如果 edittext 位于 Fragment 中,则不起作用。
4赞 Albert Oclarit 2/10/2011 #6

尝试

edit.setInputType(InputType.TYPE_NULL);

edit.setEnabled(false);
18赞 Jim 2/13/2011 #7

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

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

这似乎符合我的预期。无需处理配置更改等。对于具有冗长 TextView(说明)的活动,我需要它。

评论

1赞 CJBS 12/2/2015
为什么不直接使用根视图本身来执行此操作呢?
8赞 drei01 2/15/2011 #8

我使用以下代码来阻止 EditText 在按下按钮时窃取焦点。

addButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        View focused = internalWrapper.getFocusedChild();
        focused.setVisibility(GONE);
        v.requestFocus();
        addPanel();
        focused.setVisibility(VISIBLE);
    }
});

Basically, hide the edit text and then show it again. This works for me as the EditText is **not** in view so it doesn't matter whether it is showing.

You could try hiding and showing it in succession to see if that helps it lose focus.
29赞 Sid 3/8/2011 #9

如果您对自己的活动有其他视图,例如 ,您还可以执行以下操作:ListView

ListView.requestFocus(); 

在您的 中,从 .onResume()editText

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

89赞 Someone Somewhere 5/27/2011 #10

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

在布局 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();
}

评论

2赞 DIRTY DAVE 12/30/2021
这实际上是唯一对我有用的答案。添加可防止 EditTexts 在某些设备上获得焦点,但在某些设备上它仍然不起作用。我一直在寻找解决方案很长一段时间,这非常有效。非常感谢。android:focusable="true" android:focusableInTouchMode="true"
0赞 Jerry101 7/31/2022
这比其他技术效果更好!例如,强制文本字段散焦大多有效,但它破坏了该功能的第二次和以后的使用(平移窗口内容以使用软键盘适合文本字段),至少在 API 22-23 上是这样。onResume()adjustPan
28赞 Jack Slater 6/12/2011 #11

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

<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();
44赞 Zeus 11/7/2011 #12

您只需将 “focusable” 和 “focusable in touch mode” 设置为值 true。这样,当活动开始时,将聚焦,但由于其性质,您将在屏幕上看不到任何聚焦,当然,也不会显示键盘......TextViewlayoutTextView

53赞 rallat 12/1/2011 #13

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

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

评论

2赞 rallat 6/7/2012
android:windowSoftInputMode=“adjustPan” 在 Android 清单中的任何活动上
1204赞 Silver 12/27/2011 #14

存在一个更简单的解决方案。在父布局中设置以下属性:

<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"

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

感谢纪尧姆。

14赞 atul 2/14/2012 #15
<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"/>
100赞 floydaddict 3/13/2012 #16

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

请确保删除 XML 标记中声明末尾的以下行:EditText

<requestFocus />

这应该给出类似的东西:

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

   //<requestFocus /> /* <-- without this line */
</EditText>
84赞 MinceMan 6/15/2012 #17

以下内容在创建时将停止对焦,但在触摸它们时会抓住它。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,即不使用事件,因此聚焦行为将照常进行。

评论

7赞 Jayesh 3/8/2013
但这在未来永远不会获得焦点,如何仅在初始(活动开始)时停止焦点?
1赞 MinceMan 3/10/2013
onTouchListener 在其他触摸操作之前调用。因此,通过启用可聚焦触摸,标准聚焦发生在第一次触摸时。键盘会出现,一切都会出现。
0赞 Jerry101 3/28/2022
好!这个有效(尽管它似乎将字段从焦点处理 TAB 序列中移除)。这可以在一个地方完成,而无需布局 XML 部分:if (Build.VERSION.SDK_INT <= 27) {et.setFocusable(false); et.setOnTouchListener(...);}
38赞 jakeneff 9/28/2012 #18

我需要以编程方式明确关注所有领域。我刚刚将以下两个语句添加到了我的主布局定义中。

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

就是这样。立即解决了我的问题。谢谢,西尔弗,为我指明了正确的方向。

76赞 Lee Yi Hong 11/28/2012 #19

我已经单独尝试了几个答案,但重点仍然在 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

( 参考资料自 https://stackoverflow.com/a/9681809floydaddict )

评论

2赞 Nav 9/9/2014
除了上述内容之外,我还必须添加edittext.clearFocus()才能使其:)
14赞 Lumis 1/3/2013 #20

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

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

这会阻止软键盘出现,并且 EditText 中没有光标闪烁。

20赞 workingkills 4/24/2013 #21

由于我不喜欢用与功能相关的东西污染 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;
}
9赞 Compaq LE2202x 5/23/2013 #22

在 Activity 中,只需在 EditText 元素上添加 use。 例如onCreateclearFocus()

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

如果你想把焦点转移到另一个元素上,就用它来。 例如requestFocus()

button = (Button) findViewById(R.id.button);
button.requestFocus();
6赞 Muhammad Aamir Ali 5/31/2013 #23

确保从 xml 中的标记中删除该行。"<requestFocus />"EditText

<EditText
   android:id="@+id/input"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">

   <requestFocus /> <!-- remove this line --> 
</EditText>
3赞 MSIslam 6/6/2013 #24

EditText在 A 中无法正常工作。使用 时,最好与自动生成的行一起使用。ListViewTableLayoutEditText

3赞 Mary's 12/6/2013 #25

您可以使用请求焦点指定其他小部件的焦点,也可以使用键盘隐藏代码。

50赞 Sergey Sheleg 3/17/2014 #26

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

android:windowSoftInputMode="stateAlwaysHidden"

评论

7赞 katzenhut 9/4/2014
严格来说,这并不能解决问题。OP 说:“我不希望任何控件在启动时都具有输入焦点。您的解决方案只隐藏了键盘,两者之间有微妙的区别。
0赞 Zach 1/15/2017
@katzenhut是的,这正是我对这个答案的问题。专注于我的编辑文本会打开一个 PlaceAutoComplete 活动,因此此答案不完整
0赞 Martin Marconcini 3/21/2018
如果问题是:我如何始终确保我的活动从不显示键盘,那么这个答案将是完整的。但事实并非如此。
42赞 Babar Sanah 4/8/2014 #27

以下内容对我有用。写Manifest

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

评论

2赞 A. Rager 11/2/2016
这不会取消文本字段的焦点:它只是隐藏键盘。您仍会收到一个被推出字段的提示,并且任何颜色状态选择器都将显示“focused=true”状态。
14赞 android developer 5/14/2014 #28

对我来说,在所有设备上都有效的是:

    <!-- 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" />

只需将其作为有问题的焦点视图之前的视图,仅此而已。

2赞 Amit Yadav 5/27/2014 #29

在 onCreate() 中禁用它

final KeyListener edtTxtMessageKeyListener = edtTxtMessage.getKeyListener();
edtTxtMessage.setCursorVisible(false);
edtTxtMessage.setKeyListener(null);

最后在 EditText 的 onClick() 中启用它

edtTxtMessage.setCursorVisible(true);
edtTxtMessage.setKeyListener(edtTxtMessageKeyListener);

但问题是我们必须点击 twise 才能第一次带来 OnScreenKeyboard。

@Workaround

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

在 onClick() 中也可以尝试此操作:)

2赞 j2emanue 6/13/2014 #30

我遇到了这样的问题,这是由于我的选择器造成的。第一种状态是焦点,即使我的视图被禁用,它也采用了焦点状态,因为它是第一个匹配和使用它的状态。您可以将第一个状态设置为禁用,如下所示:

<selector xmlns:android="http://schemas.android.com/apk/res/android">


<item android:drawable="@drawable/text_field_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/text_field_focused" android:state_focused="true"/>
<item android:drawable="@drawable/text_field_normal"/>

2赞 Akshay Paliwal 2/4/2015 #31

从 IN 文件中删除。<requestFocus />EditTextxml

<EditText
       android:id="@+id/emailField"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:inputType="textEmailAddress">
    
       //`<requestFocus />` /* <-- remove this tags */
    </EditText>

评论

1赞 Hermandroid 2/19/2015
我只是在我的父布局上使用android:focusableInTouchMode=“true”并为我工作。
12赞 user4728480 3/31/2015 #32

这是完美而简单的解决方案。我总是在我的应用程序中使用它。
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

评论

1赞 A. Rager 11/2/2016
这不会取消文本字段的焦点:它只是隐藏键盘。您仍会收到一个被推出字段的提示,并且任何颜色状态选择器都将显示“focused=true”状态。
3赞 Mahmudul Haque Khan 4/21/2015 #33
<EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:id="@+id/etComments"
    android:hint="Comments.."
    android:textSize="14dp"
    android:focusable="false"
    android:textStyle="italic"/>
8赞 Ish 6/14/2015 #34

为此,您可以创建一个将布局宽度和高度设置为 的虚拟文件,并请求焦点到该视图。 在 xml 布局中添加以下代码片段:EditText0dp

<EditText
    android:id="@+id/editText0"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/dummy"
    android:ems="10" 
    >
     <requestFocus />
    </EditText>
33赞 prgmrDev 6/24/2015 #35

添加文件的活动标记。android:windowSoftInputMode="stateAlwaysHidden"Manifest.xml

评论

1赞 A. Rager 11/2/2016
这不会取消文本字段的焦点:它只是隐藏键盘。您仍会收到一个被推出字段的提示,并且任何颜色状态选择器都将显示“focused=true”状态。
4赞 ceph3us 7/10/2015 #36
/** 
 * set focus to top level window
 * disposes descendant focus 
 * disposes softInput 
 * */
public static void topLevelFocus(Context context){
    if(Activity.class.isAssignableFrom(context.getClass())){
        ViewGroup tlView = (ViewGroup) ((Activity) context).getWindow().getDecorView();
        if(tlView!=null){
            tlView.setFocusable(true);
            tlView.setFocusableInTouchMode(true);
            tlView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        }
    }
}
24赞 Vishal Raj 12/21/2015 #37

在方法中添加以下内容:onCreate

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

评论

2赞 A. Rager 11/2/2016
这不会取消文本字段的焦点:它只是隐藏键盘。您仍会收到一个被推出字段的提示,并且任何颜色状态选择器都将显示“focused=true”状态。
2赞 Karthik 8/24/2016 #38

最简单的方法是添加 Manifest.xml 文件的活动标记android:windowSoftInputMode="stateAlwaysHidden"

评论

2赞 A. Rager 11/2/2016
这不会取消文本字段的焦点:它只是隐藏键盘。您仍会收到一个被推出字段的提示,并且任何颜色状态选择器都将显示“focused=true”状态。
11赞 Tarit Ray 9/22/2016 #39

将此代码写在您不想打开键盘的文件中。ManifestActivity

android:windowSoftInputMode="stateHidden"

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.project"
    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>

评论

3赞 A. Rager 11/2/2016
这不会取消文本字段的焦点:它只是隐藏键盘。您仍会收到一个被推出字段的提示,并且任何颜色状态选择器都将显示“focused=true”状态。
7赞 DkPathak 9/28/2016 #40
View current = getCurrentFocus();

if (current != null) 
    current.clearFocus();
2赞 Tulsi 1/2/2017 #41

这样做并完成您的工作!

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

评论

0赞 Ricardo A. 6/4/2019
重复答案
7赞 Mansuu.... 1/16/2017 #42

当您的活动被打开时,键盘会自动可见,这会导致 EditText 的焦点。您可以通过在 manifest.xml 文件的活动标记中编写以下行来禁用键盘。

android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
21赞 Vishal Vaishnav 7/26/2017 #43

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

 android:focusableInTouchMode="true"

评论

0赞 Ricardo A. 6/4/2019
重复答案
9赞 Sharath kumar 9/11/2017 #44

隐藏键盘的最简单方法是使用 setSoftInputMode

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

或者你可以使用 InputMethodManager 并像这样隐藏键盘。

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

评论

0赞 Ricardo A. 6/4/2019
问题与键盘无关
74赞 Rishabh Saxena 4/18/2018 #45

较晚但最简单的答案,只需将其添加到XML的父布局中即可。

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

如果它对你有帮助,请投赞成票!快乐编码:)

评论

4赞 Karthic Srinivasan 12/29/2018
对我来说非常完美。还有一点需要注意的是,不要将这些行添加到滚动视图中。它在滚动视图中不起作用。但与线性布局完美配合。
5赞 hassan mirza 9/9/2018 #46

你有 和 .在 OnStart/On Create 中,应将焦点设置在 listview 上:Edittextlistlistview.requestfocus()

评论

0赞 rgv 3/6/2019
我喜欢这个,因为它足够简单和干净
4赞 mmBs 1/2/2019 #47

它可以通过继承和覆盖来实现。EditTextonTouchEvent

class NonFocusableEditText: EditText {

    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet?): super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr)

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return if (isFocusable) super.onTouchEvent(event) else false
    }
}

然后,您可以像往常一样在布局中使用它:EditText

<com.yourpackage.NonFocusableEditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"    
        android:hint="@string/your_hint"
        android:imeOptions="actionDone"
        android:inputType="textNoSuggestions" />
-5赞 Akash Suresh Dandwate 2/22/2019 #48

在清单文件中添加以下行,其中提到了您的活动

android:windowSoftInputMode="stateAlwaysHidden"

评论

2赞 Dan 3/29/2019
这将防止键盘出现,这不是所要求的。
1赞 Rohit Patil 5/11/2019 #49

如果要在活动开始时隐藏键盘。然后提及

android:windowSoftInputMode="stateHidden"

添加到清单文件中的该活动。问题得到解决。

干杯。

1赞 Bukunmi 7/28/2019 #50

我用提交按钮清除所有焦点

XML 文件:

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

JAVA 文件:

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

            }
        });

我希望这对你有所帮助:)

1赞 Jyotiprakash Das 9/16/2019 #51

一个简单可靠的解决方案,只需覆盖此方法:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null &&
            (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
            v instanceof EditText &&
            !v.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        v.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + v.getLeft() - scrcoords[0];
        float y = ev.getRawY() + v.getTop() - scrcoords[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom())
            hideKeyboard(this);
    }
    return super.dispatchTouchEvent(ev);
}

public static void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
    }
}
4赞 Amir Raza 11/27/2019 #52

只需添加 EditText 的父布局,您就可以摆脱这种尴尬的行为。android:focusableInTouchMode="true"

1赞 Haris 12/9/2020 #53

已经提供了许多可行的答案,但我认为我们可以通过使用以下简单的方法做得更好

//set focus to input field
private fun focusHere() {
    findViewById<TextView>(R.id.input).requestFocus()
}

代替 R.id.input 中的输入,使用任何其他视图 ID 将焦点设置为该视图。

评论

0赞 Sayed Idrees 1/6/2021
问题是关于失去焦点。
0赞 Haris 7/1/2021
您将失去您需要的一个视图的焦点,并将其设置为另一个视图
1赞 DeveloperForce 6/29/2021 #54

您可以将 Editext 设置为禁用焦点属性,现在可以通过两种方式应用:

  • 您可以禁用可聚焦作为常规属性

  • 或者,您可以在触摸模式(触摸屏)中禁用 FocusableInTouchMode 作为特定于该视图的属性

默认情况下,如果 Editext 位于该活动中视图堆栈的顶部(例如,标题),则 Focusable 属性为 true,则在活动启动时可聚焦。

要禁用 Focusable,您只需将其布尔值设置为 false。

所以这将是:

android:focusable="false"

要禁用它 FocusableInTouchMode,您只需将其布尔值设置为 false。 所以这将是:

android:focusable="false"

您只需找到要应用更改的文本视图,并将相应的代码段添加到 XML 文件中的 xml 规范中即可。

或者,您可以单击布局编辑器中的文本视图,找到显示该文本视图的所有 xml 属性的侧边栏,然后向下滚动到声明“Focusable”和“FocusableInTouchMode”的位置,并检查它们是 true 还是 false。