提问人:Mark 提问时间:10/12/2009 最后编辑:Ramesh RMark 更新时间:9/28/2022 访问量:824450
当活动在 Android 中开始时,如何阻止 EditText 获得焦点?
How to stop EditText from gaining focus when an activity starts in Android?
问:
我在 Android 中有一个,有两个元素:Activity
EditText
ListView
当我启动时,立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我试过了:Activity
EditText
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。我怎样才能说服它在开始时不选择自己?EditText
Activity
答:
尝试使用 clearFocus() 而不是 .Android 中的每个视图都具有可聚焦性和可选择性,我认为您只想清除焦点。setSelected(false)
评论
myEditText.clearFocus(); myDummyLinearLayout.requestFocus();
onResume
我找到的唯一解决方案是:
- 创建一个 LinearLayout(我不知道其他类型的布局是否有效)
- 设置属性和
android:focusable="true"
android:focusableInTouchMode="true"
而且在开始活动后不会得到焦点EditText
评论
是的,我做了同样的事情 - 创建一个“虚拟”线性布局,以获得初始焦点。此外,我设置了“下一个”焦点 ID,以便用户在滚动一次后无法再聚焦它:
<LinearLayout 'dummy'>
<EditText et>
dummy.setNextFocusDownId(et.getId());
dummy.setNextFocusUpId(et.getId());
et.setNextFocusUpId(et.getId());
很多工作只是为了摆脱对视图的关注。
谢谢
将标签和添加到父布局(例如 或 ) (如以下示例所示)将解决问题。android:focusableInTouchMode="true"
android:focusable="true"
LinearLayout
ConstraintLayout
<!-- 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"/>
评论
android:focusableInTouchMode="true"
实际问题是你根本不想让它集中注意力吗?或者您不希望它显示虚拟键盘,因为专注于 ?我真的没有看到将焦点放在开始上的问题,但是当用户没有明确请求将焦点放在(并因此打开键盘)时,打开 softInput 窗口绝对是一个问题。EditText
EditText
EditText
如果是虚拟键盘的问题,请参阅 <activity> 元素文档。AndroidManifest.xml
android:windowSoftInputMode="stateHidden"
- 进入活动时始终将其隐藏。
或者 - 不要更改它(例如,如果它尚未显示,则不显示它,但如果它在进入活动时处于打开状态,请将其保持打开状态)。android:windowSoftInputMode="stateUnchanged"
评论
EditText
EditText
尝试
edit.setInputType(InputType.TYPE_NULL);
edit.setEnabled(false);
迟到了,但也许有帮助。在布局顶部创建一个虚拟的 EditText,然后调用myDummyEditText.requestFocus()
onCreate()
<EditText android:id="@+id/dummyEditTextFocus"
android:layout_width="0px"
android:layout_height="0px" />
这似乎符合我的预期。无需处理配置更改等。对于具有冗长 TextView(说明)的活动,我需要它。
评论
我使用以下代码来阻止 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.
如果您对自己的活动有其他视图,例如 ,您还可以执行以下操作:ListView
ListView.requestFocus();
在您的 中,从 .onResume()
editText
我知道这个问题已经得到解答,但只是提供一个对我有用的替代解决方案:)
使用其他海报提供的信息,我使用了以下解决方案:
在布局 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();
}
评论
android:focusable="true" android:focusableInTouchMode="true"
onResume()
adjustPan
在第一个可编辑字段之前尝试以下操作:
<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();
您只需将 “focusable” 和 “focusable in touch mode” 设置为值 true。这样,当活动开始时,将聚焦,但由于其性质,您将在屏幕上看不到任何聚焦,当然,也不会显示键盘......TextView
layout
TextView
这些解决方案都不适合我。我修复自动对焦的方法是:
<activity android:name=".android.InviteFriendsActivity"
android:windowSoftInputMode="adjustPan">
<intent-filter >
</intent-filter>
</activity>
评论
存在一个更简单的解决方案。在父布局中设置以下属性:
<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();
android:descendantFocusability="beforeDescendants"
似乎是 默认值(整数值为 0)。它只需添加 .android:focusableInTouchMode="true"
实际上,我们可以看到在方法(Android 2.2.2)中将其设置为默认值。但不等于 0。beforeDescendants
ViewGroup.initViewGroup()
ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;
感谢纪尧姆。
<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"/>
问题似乎来自我只能在布局中看到的属性。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>
以下内容在创建时将停止对焦,但在触摸它们时会抓住它。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,即不使用事件,因此聚焦行为将照常进行。
评论
if (Build.VERSION.SDK_INT <= 27) {et.setFocusable(false); et.setOnTouchListener(...);}
我需要以编程方式明确关注所有领域。我刚刚将以下两个语句添加到了我的主布局定义中。
myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);
就是这样。立即解决了我的问题。谢谢,西尔弗,为我指明了正确的方向。
我已经单独尝试了几个答案,但重点仍然在 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
)
评论
我做的最简单的事情是在onCreate中将焦点设置在另一个视图上:
myView.setFocusableInTouchMode(true);
myView.requestFocus();
这会阻止软键盘出现,并且 EditText 中没有光标闪烁。
由于我不喜欢用与功能相关的东西污染 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;
}
在 Activity 中,只需在 EditText 元素上添加 use。
例如onCreate
clearFocus()
edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();
如果你想把焦点转移到另一个元素上,就用它来。
例如requestFocus()
button = (Button) findViewById(R.id.button);
button.requestFocus();
确保从 xml 中的标记中删除该行。"<requestFocus />"
EditText
<EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<requestFocus /> <!-- remove this line -->
</EditText>
EditText
在 A 中无法正常工作。使用 时,最好与自动生成的行一起使用。ListView
TableLayout
EditText
您可以使用请求焦点指定其他小部件的焦点,也可以使用键盘隐藏代码。
简单的解决方案:
在标签中使用AndroidManifest
Activity
android:windowSoftInputMode="stateAlwaysHidden"
评论
以下内容对我有用。写Manifest
<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
评论
对我来说,在所有设备上都有效的是:
<!-- 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" />
只需将其作为有问题的焦点视图之前的视图,仅此而已。
在 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() 中也可以尝试此操作:)
我遇到了这样的问题,这是由于我的选择器造成的。第一种状态是焦点,即使我的视图被禁用,它也采用了焦点状态,因为它是第一个匹配和使用它的状态。您可以将第一个状态设置为禁用,如下所示:
<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"/>
从 IN 文件中删除。<requestFocus />
EditText
xml
<EditText
android:id="@+id/emailField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress">
//`<requestFocus />` /* <-- remove this tags */
</EditText>
评论
这是完美而简单的解决方案。我总是在我的应用程序中使用它。
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
评论
<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"/>
为此,您可以创建一个将布局宽度和高度设置为 的虚拟文件,并请求焦点到该视图。
在 xml 布局中添加以下代码片段:EditText
0dp
<EditText
android:id="@+id/editText0"
android:layout_width="0dp"
android:layout_height="0dp"
android:hint="@string/dummy"
android:ems="10"
>
<requestFocus />
</EditText>
添加文件的活动标记。android:windowSoftInputMode="stateAlwaysHidden"
Manifest.xml
评论
/**
* 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);
}
}
}
在方法中添加以下内容:onCreate
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
评论
最简单的方法是添加 Manifest.xml 文件的活动标记android:windowSoftInputMode="stateAlwaysHidden"
评论
将此代码写在您不想打开键盘的文件中。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.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>
评论
View current = getCurrentFocus();
if (current != null)
current.clearFocus();
这样做并完成您的工作!
android:focusable="true"
android:focusableInTouchMode="true"
评论
当您的活动被打开时,键盘会自动可见,这会导致 EditText 的焦点。您可以通过在 manifest.xml 文件的活动标记中编写以下行来禁用键盘。
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
在你的父布局中写下这一行...
android:focusableInTouchMode="true"
评论
隐藏键盘的最简单方法是使用 setSoftInputMode
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
或者你可以使用 InputMethodManager 并像这样隐藏键盘。
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
评论
较晚但最简单的答案,只需将其添加到XML的父布局中即可。
android:focusable="true"
android:focusableInTouchMode="true"
如果它对你有帮助,请投赞成票!快乐编码:)
评论
你有 和 .在 OnStart/On Create 中,应将焦点设置在 listview 上:Edittext
list
listview.requestfocus()
评论
它可以通过继承和覆盖来实现。EditText
onTouchEvent
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" />
在清单文件中添加以下行,其中提到了您的活动
android:windowSoftInputMode="stateAlwaysHidden"
评论
如果要在活动开始时隐藏键盘。然后提及
android:windowSoftInputMode="stateHidden"
添加到清单文件中的该活动。问题得到解决。
干杯。
我用提交按钮清除所有焦点
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
}
});
我希望这对你有所帮助:)
一个简单可靠的解决方案,只需覆盖此方法:
@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);
}
}
只需添加 EditText 的父布局,您就可以摆脱这种尴尬的行为。android:focusableInTouchMode="true"
已经提供了许多可行的答案,但我认为我们可以通过使用以下简单的方法做得更好
//set focus to input field
private fun focusHere() {
findViewById<TextView>(R.id.input).requestFocus()
}
代替 R.id.input 中的输入,使用任何其他视图 ID 将焦点设置为该视图。
评论
您可以将 Editext 设置为禁用焦点属性,现在可以通过两种方式应用:
您可以禁用可聚焦作为常规属性
或者,您可以在触摸模式(触摸屏)中禁用 FocusableInTouchMode 作为特定于该视图的属性
默认情况下,如果 Editext 位于该活动中视图堆栈的顶部(例如,标题),则 Focusable 属性为 true,则在活动启动时可聚焦。
要禁用 Focusable,您只需将其布尔值设置为 false。
所以这将是:
android:focusable="false"
要禁用它 FocusableInTouchMode,您只需将其布尔值设置为 false。 所以这将是:
android:focusable="false"
您只需找到要应用更改的文本视图,并将相应的代码段添加到 XML 文件中的 xml 规范中即可。
或者,您可以单击布局编辑器中的文本视图,找到显示该文本视图的所有 xml 属性的侧边栏,然后向下滚动到声明“Focusable”和“FocusableInTouchMode”的位置,并检查它们是 true 还是 false。
评论