安卓按钮需点击两次才能执行动作。

22

我有一个表单。垂直布局中有7个EditText。在屏幕上一次只能看到3个EditText(表单很大,因此我需要上下滚动来填写所有字段)。在底部有按钮。

当我填写顶部EditText(或顶部其中一个EditText,在向下滚动到按钮时不可见),并且焦点(光标)在此EditText中时,当我向下滚动并尝试单击按钮时,第一次单击无效,再次单击才会触发按钮操作。

当具有焦点的EditText和按钮都可见时-按钮需要单击一次。

我认为在第一种情况下,第一次点击只是获取焦点。而第二次点击是“真正”的点击。

我该怎么办?我只需要一次单击按钮。


如何重复此操作: 创建带有默认活动的空项目,使用此布局http://pastebin.ca/2054854 在真实设备上启动项目 - 将文本写入顶部EditText,滚动到按钮并单击按钮。 - newmindcore
4个回答

29

这个问题很老了,我不知道这是否能解决您的问题,因为您过去的链接不再有效,但由于我在寻找同样问题的帖子时找到了解决方案,所以我仍然会发布它:

在我的情况下,当我按照教程将自定义样式应用于按钮时,出现了这个问题:

<style name="ButtonStyle" parent="@android:style/Widget.Holo.Button">
    <item name="android:focusable">true</item>
    <item name="android:focusableInTouchMode">true</item>
    <item name="android:clickable">true</item>
    <item name="android:background">@drawable/custom_button</item>
    <item name="android:textColor">@color/somecolor</item>
    <item name="android:gravity">center</item>
</style>
问题出在以下这行代码:
<item name="android:focusableInTouchMode">true</item>

我一旦删除它,按钮就按预期工作了。

希望这能帮到您。


谢谢!这为我解决了问题。 - locke
那个在古老的教程中错误地发布的“focusableInTouchMode”已经被复制粘贴到了无数存在缺陷的Android应用程序中。 - Greg Ennis

14
我曾用以下方法解决类似问题。如果第一次点击只是获取焦点,它会自动再次点击该项:
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    v.performClick();
                }
            }
        });

我需要将focusableInTouchMode设置为true。


你救了我的命,老兄 :) - iBabur
@Rajkiran 如果需要 android:focusableInTouchMode="true",那么这个解决方案是完美的。在我的情况下,必须将 focusableInTouchMode 设置为 true。 - iBabur
顺便提一下,在被接受的答案中,按钮也具有属性focusableInTouchMode设置为true。 :) - Rajkiran
1
被接受的答案说,为了让这个解决方案起作用,必须删除该行。 - user2137040
2
这可能会有问题,因为如果按钮获得焦点但没有被点击,则会执行单击操作。例如,键盘连接到Android设备并且正在使用Tab键切换焦点。 - A.J.Bauer

2
与Mave的答案类似,以下这种方法对我有效:
<Button 
    style="@android:style/Widget.EditText"
    android:focusableInTouchMode="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

1

虽然这是一个老问题,但我也遇到了同样的问题,需要使按钮可聚焦。
最终,我使用了OnTouchListener。

myButton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            // do your stuff on down here
        } else if (action == MotionEvent.ACTION_UP) {
            // do your stuff on up here
        }

        // if you return true then the event is not bubbled e.g. if you don't want the control to get focus or other handlers..

        return false;                 
    }
});

谢谢!我一直在尝试在自定义视图中指示焦点,所以我不得不启用 focusableInTouchMode,这样按钮需要两次轻触。这个解决方案很完美,并且比 onClick 方法更不容易产生奇怪的副作用。 - Sakiboy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接