我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
当前回答
在父布局(例如LinearLayout或ConstraintLayout)中添加标签android:focusableInTouchMode=“true”和android:focusable=“true”将解决该问题。
<!-- 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"/>
其他回答
利用其他海报提供的信息,我使用了以下解决方案:
在布局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();
}
我需要以编程方式明确关注所有领域。我刚刚在主布局定义中添加了以下两条语句。
myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);
就这样。立刻解决了我的问题。谢谢,西尔弗,你给我指明了正确的方向。
以下内容在Manifest中对我有效。写
<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
我做的最简单的事情是在onCreate中设置另一个视图的焦点:
myView.setFocusableInTouchMode(true);
myView.requestFocus();
这阻止了软键盘的出现,并且EditText中没有光标闪烁。
已经提供了很多有效的答案,但我认为我们可以使用以下简单方法做得更好
//set focus to input field
private fun focusHere() {
findViewById<TextView>(R.id.input).requestFocus()
}
使用任何其他视图id来设置该视图的焦点,以代替R.id.input中的输入。