我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
当前回答
<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"/>
其他回答
try
edit.setInputType(InputType.TYPE_NULL);
edit.setEnabled(false);
存在更简单的解决方案。在父布局中设置这些属性:
<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:focuableInTouchMode=“true”。
实际上,我们可以看到,在ViewGroup.initViewGroup()方法中,beforeDescendants被设置为默认值(Android 2.2.2)。但不等于0。ViewGroup.FOCUS_BEFORE_DESCENTANS=0x20000;
感谢纪尧姆。
我需要以编程方式明确关注所有领域。我刚刚在主布局定义中添加了以下两条语句。
myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);
就这样。立刻解决了我的问题。谢谢,西尔弗,你给我指明了正确的方向。
以下内容将阻止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,即不使用事件,所以聚焦行为将照常进行。
对我来说,在所有设备上工作的是:
<!-- 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" />
只需将此作为一个视图放在有问题的聚焦视图之前,就可以了。