Android:强制 EditText 删除焦点?

发布于 2024-10-18 09:34:08 字数 69 浏览 5 评论 0原文

我希望能够从 EditText 中删除焦点。例如,如果键盘出现,并且用户使用后退按钮隐藏它,我希望焦点和光标消失。怎么办呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

纵情客 2024-10-25 09:34:08

您可以通过以下方式使光标和焦点消失,

edittext.clearFocus();

但检测键盘何时隐藏是一项艰巨的工作。

You can make cursor and focus disappear by

edittext.clearFocus();

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

长途伴 2024-10-25 09:34:08

您可以将其添加到 onCreate 中,每次 Activity 启动时它都会隐藏键盘。

您还可以通过编程方式将焦点更改为另一个项目。

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

You can add this to onCreate and it will hide the keyboard every time the Activity starts.

You can also programmatically change the focus to another item.

 this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
梦行七里 2024-10-25 09:34:08

在 XML 中的 EditText 之前添加 LinearLayout

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

或者,您可以通过在“EditText”之前添加这些行以查看来执行相同的操作。

<Button
    android:id="@+id/btnSearch"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center"
    android:text="Quick Search"
    android:textColor="#fff"
    android:textSize="13sp"
    android:textStyle="bold" />

<EditText
    android:id="@+id/edtSearch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:gravity="left"
    android:hint="Name"
    android:maxLines="1"
    android:singleLine="true"
    android:textColorHint="@color/blue"
    android:textSize="13sp"
    android:textStyle="bold" />

Add LinearLayout before EditText in your XML.

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

Or you can do this same thing by adding these lines to view before your 'EditText'.

<Button
    android:id="@+id/btnSearch"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center"
    android:text="Quick Search"
    android:textColor="#fff"
    android:textSize="13sp"
    android:textStyle="bold" />

<EditText
    android:id="@+id/edtSearch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:gravity="left"
    android:hint="Name"
    android:maxLines="1"
    android:singleLine="true"
    android:textColorHint="@color/blue"
    android:textSize="13sp"
    android:textStyle="bold" />
花开半夏魅人心 2024-10-25 09:34:08

移除焦点但保持可聚焦:

editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);

EditText 将失去焦点,但可以在新的触摸事件上再次获得焦点。

Remove focus but remain focusable:

editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);

EditText will lose focus, but can gain it again on a new touch event.

可是我不能没有你 2024-10-25 09:34:08

将这两个属性添加到您的父布局(例如:线性布局、相对布局)中

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

即可解决问题:)

Add these two properties to your parent layout (ex: Linear Layout, Relative Layout)

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

It will do the trick :)

A君 2024-10-25 09:34:08

删除自动对焦 edittext android

它对我有用

编辑 在链接中,他们建议使用 LinearLayout,但简单的 View 就可以工作

<View
    android:id="@+id/focus_thief"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:focusable="true"
    android:focusableInTouchMode="true" />

然后,如果这个“小偷”被放置在布局的顶部(成为第一个可聚焦项目),则调用 clearFocus() 将起作用。

remove autofocus edittext android

It's working for me

Edit In the link they suggest to use LinearLayout, but simple View will work

<View
    android:id="@+id/focus_thief"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:focusable="true"
    android:focusableInTouchMode="true" />

Then if this "thief" is placed at the top of the layout (to be first focusable item) calls to clearFocus() will work.

无风消散 2024-10-25 09:34:08

您还可以在清单操作部分中包含 android:windowSoftInputMode="stateAlwaysHidden"

这相当于 :

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

,但采用 XML 方式。

仅供参考,您还可以使用代码隐藏键盘:

// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);

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);
仅此而已 2024-10-25 09:34:08

要在活动开始时隐藏键盘.. 在 onCreate() 中编写以下代码..

InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

要清除焦点并从 edittext 中删除光标......

editText.clearFocus();

editText.setCursorVisible(false);

To hide the keyboard when activity starts.. write the following code in onCreate()..

InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

To clear focus and remove cursor from edittext.....

editText.clearFocus();

editText.setCursorVisible(false);
自控 2024-10-25 09:34:08

尝试在您的视图中使用这个
它对我有用:

<View
    android:id="@+id/fucused"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"/>

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"/>
半透明的墙 2024-10-25 09:34:08

添加到您的父布局中,您将 EditText 这个 android:focusableInTouchMode="true" 放在哪里

Add to your parent layout where did you put your EditText this android:focusableInTouchMode="true"

荒岛晴空 2024-10-25 09:34:08

如果您不使用

并且仍然存在相同的问题用户 LinearLayout 作为父级,则必须删除 并设置

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

希望它对您有帮助。

you have to remove <requestFocus/>

if you don't use it and still the same problem

user LinearLayout as a parent and set

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

Hope it's help you.

尐偏执 2024-10-25 09:34:08

这是我第一次回答这个问题,如果有错误,请不要对我太严厉。 :D

围绕 SO 的答案很少,但我很想发布我的完整解决方案,因为这让我发疯。我已经从各地抓取了一些零碎的东西,所以如果我没有给每个人相应的学分,请原谅我......:)

(我会简化我的结果,因为我的视图有太多元素,我不想垃圾邮件并且会尝试使其尽可能通用...)

对于您的布局,您需要一个父级,您的 EditText父视图 定义如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
              android:orientation="vertical"
              android:layout_width="match_parent" 
              android:layout_height="match_parent"
              android:id="@+id/lytContainer"
              android:descendantFocusability="beforeDescendants"
              android:focusableInTouchMode="true">
<EditText android:layout_width="fill_parent" 
              android:layout_height="wrap_content" 
              android:id="@+id/etEditor"
              android:inputType="number"
              android:layout_gravity="center" 
              android:hint="@string/enter_your_text"
              android:textColor="@android:color/darker_gray" 
              android:textSize="12dp"
              android:textAlignment="center" 
              android:gravity="center" 
              android:clickable="true"/>
</LinearLayout>

所以,我需要这里有一些事情。我需要为我的 EditText 有一个占位符 - 就是这样 -

android:hint="提示"

另外,

android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

使 EditText 不会专注于输入 Activity 以及稍后的 Activity 本身设置它时,此设置会有所帮助,因此您可以在其上设置onTouchListener以将焦点从EditText上夺走。

现在,在活动中:

package com.at.keyboardhide;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

public class MainActivity extends Activity implements OnTouchListener{
private EditText getEditText;
private LinearLayout getLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    setContentView(R.layout.keyboardmain);
    getEditText = (EditText)findViewById(R.id.etEditor);
    getLinearLayout = (LinearLayout)findViewById(R.id.lytContainer);
    getLinearLayout.setOnTouchListener(this);

    getEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Log.d("EDTA", "text was entered.");
                getEditText.clearFocus();
                imm.hideSoftInputFromWindow(barcodeNo.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });
}
@Override
public boolean onTouch(View v, MotionEvent event) {
    if(v==getLinearLayout){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getEditText.getWindowToken(), 0);
        getEditText.clearFocus();
        return true;
        }
    return false;
    }
}

我在这个问题页面上找到的一些答案,以及我在这个 博客。我错过的其余部分是我必须自己弄清楚的,那就是清除对EditText 的关注,我将其添加到 setOnEditorActionListener父视图的 onTouchLister 中嗯>。

希望这可以帮助某人并节省他们的时间。 :)

干杯,
Z。

This is my very first answer on SO, so don't be too harsh on me if there are mistakes. :D

There are few answers floating around the SO, but I feel the urge to post my complete solution cause this drove me nuts. I've grabbed bits and pieces from all around so forgive me if I don't give respective credits to everyone... :)

(I'll simplify my result cause my view has too many elements and I don't wanna spam with that and will try to make it as generic as possible...)

For your layout you need a parent your EditText and parent view defined something like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
              android:orientation="vertical"
              android:layout_width="match_parent" 
              android:layout_height="match_parent"
              android:id="@+id/lytContainer"
              android:descendantFocusability="beforeDescendants"
              android:focusableInTouchMode="true">
<EditText android:layout_width="fill_parent" 
              android:layout_height="wrap_content" 
              android:id="@+id/etEditor"
              android:inputType="number"
              android:layout_gravity="center" 
              android:hint="@string/enter_your_text"
              android:textColor="@android:color/darker_gray" 
              android:textSize="12dp"
              android:textAlignment="center" 
              android:gravity="center" 
              android:clickable="true"/>
</LinearLayout>

So, I needed a few things here. I needed to have a Placeholder for my EditText - which is that -

android:hint="hint"

Also,

android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

made it happen for EditText not to be focused on entering the Activity and later on in the Activity itself when setting it this setting helps so you can set onTouchListener on it to steal the focus away from EditText.

Now, in the Activity:

package com.at.keyboardhide;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

public class MainActivity extends Activity implements OnTouchListener{
private EditText getEditText;
private LinearLayout getLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    setContentView(R.layout.keyboardmain);
    getEditText = (EditText)findViewById(R.id.etEditor);
    getLinearLayout = (LinearLayout)findViewById(R.id.lytContainer);
    getLinearLayout.setOnTouchListener(this);

    getEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Log.d("EDTA", "text was entered.");
                getEditText.clearFocus();
                imm.hideSoftInputFromWindow(barcodeNo.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });
}
@Override
public boolean onTouch(View v, MotionEvent event) {
    if(v==getLinearLayout){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getEditText.getWindowToken(), 0);
        getEditText.clearFocus();
        return true;
        }
    return false;
    }
}

Few of the answers for bits I found on this question page, and the part with the Activity solution I found on this blog. The rest I missed which I had to figure out myself was clearing focus on the EditText which I added to both inside the setOnEditorActionListener and onTouchLister for the parent view.

Hope this helps someone and saves their time. :)

Cheers,
Z.

你是暖光i 2024-10-25 09:34:08

在评论中,您询问是否可以聚焦另一个视图而不是 EditText。是的,可以。对您想要在开始时聚焦的视图使用 .requestFocus() 方法(在 onCreate() 方法中)

同时聚焦其他视图会减少一些代码量。 (例如隐藏键盘的代码)

In the comments you asked if another view can be focused instead of the EditText. Yes it can. Use .requestFocus() method for the view you want to be focused at the beginning (in onCreate() method)

Also focusing other view will cut out some amount of code. (code for hiding the keyboard for example)

◇流星雨 2024-10-25 09:34:08

我也有同样的问题。这让我非常疯狂。

我有一个带有 ScrollView 的扩展对话框,其中有一个带有扩展 LinearLayout 的 TableLayout,其中包含一个 SeekBar 和一个 EditText。

第一个 EditText 在显示对话框后始终自动对焦,并且在通过键盘编辑文本后,EditText 仍然具有焦点并且键盘仍然可见。

我尝试了该线程的几乎所有解决方案,但没有一个对我有用。

所以这是我的简单解决方案:(text = EditText)

text.setOnEditorActionListener( new OnEditorActionListener( ){
    public boolean onEditorAction( TextView v, int actionId, KeyEvent event ){
        if( (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) ||
            (actionId == EditorInfo.IME_ACTION_DONE) ){
            text.clearFocus( );
            InputMethodManager iMgr = null;
            iMgr = (InputMethodManager)mContext.getSystemService( Context.INPUT_METHOD_SERVICE );
            iMgr.hideSoftInputFromWindow( text.getWindowToken(), 0 );
        }
        return true;
    }
});

顺便说一句,我没有使用以下任何代码片段来解决它:

//setFocusableInTouchMode( true )
//setFocusable( true )
//setDescendantFocusability( ViewGroup.FOCUS_BEFORE_DESCENDANTS )

而且我没有 使用了一个间隔项,例如宽度和高度为 1dp 的 View。

希望它对某人有帮助:D

I had the same problem. It made me more than crazy.

I had an extended Dialog with a ScrollView that had a TableLayout with extended LinearLayout that contained a SeekBar and a EditText.

The first EditText had always autofocus after showing the Dialog and after finishing editing the text over the keyboard the EditText still had the focus and the keyboard was still visible.

I tried nearly all solutions of this thread and none worked for me.

So here my simple solution: (text = EditText)

text.setOnEditorActionListener( new OnEditorActionListener( ){
    public boolean onEditorAction( TextView v, int actionId, KeyEvent event ){
        if( (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) ||
            (actionId == EditorInfo.IME_ACTION_DONE) ){
            text.clearFocus( );
            InputMethodManager iMgr = null;
            iMgr = (InputMethodManager)mContext.getSystemService( Context.INPUT_METHOD_SERVICE );
            iMgr.hideSoftInputFromWindow( text.getWindowToken(), 0 );
        }
        return true;
    }
});

By the way I didn't used any of the following snippets to solve it:

//setFocusableInTouchMode( true )
//setFocusable( true )
//setDescendantFocusability( ViewGroup.FOCUS_BEFORE_DESCENDANTS )

AND I didn't used a spacer item like a View with width and height of 1dp.

Hopefully it helps someone :D

深海少女心 2024-10-25 09:34:08
editText.setFocusableInTouchMode(true)

当用户触摸 EditText 时,它将能够获得焦点。
当主布局(活动、对话框等)变得可见时,EditText 不会自动获得焦点,即使它是布局中的第一个视图。

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.

顾北清歌寒 2024-10-25 09:34:08

您还可以在清单操作部分中包含 android:windowSoftInputMode="stateAlwaysHidden"

这相当于:

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

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);
旧人 2024-10-25 09:34:08

您可以通过设置父元素的属性 android:descendantFocusability 来避免对元素的任何关注。

下面是一个示例:

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

这里,属性 android:descendantFocusability 设置为“blocksDescendants”会阻止子元素上的焦点。

您可以在此处找到更多信息。

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.

魔法唧唧 2024-10-25 09:34:08
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文