【问题标题】:Android OnTouchListener deactivates button layout statesAndroid OnTouchListener 停用按钮布局状态
【发布时间】:2013-03-25 07:20:55
【问题描述】:

最初我的按钮通过 XML 连接到一个方法,如下所示:

    <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button_green"
    android:onClick="start_process"
    android:text="@string/button_send"
    android:textSize="50sp" />

然后我决定添加一个 onTouchListener 以便我可以处理 ACTION_UP 事件:

    private OnTouchListener myListener = new OnTouchListener(){
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            //start recording
            System.out.println("DOWN");
            start_process();

        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            System.out.println("UP");   
        }
        return true;
    }
};

监听器效果很好,但我注意到我的按钮状态已经消失。如果按钮被按下,则该按钮具有不同的颜色,但是现在该按钮正在通过侦听器进行交互,因此不再发生这种情况。这是@drawable/custom_button_green 中定义的内容:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" 
    android:drawable="@drawable/btn_default_pressed" />
<item android:state_focused="false" android:state_enabled="true"
    android:drawable="@drawable/btn_default_normal_green" />
<item android:state_focused="false" android:state_enabled="false"
    android:drawable="@drawable/btn_default_normal_disable" />
<item android:state_focused="true" android:state_enabled="true"
    android:drawable="@drawable/btn_default_selected" />
<item android:state_enabled="true"
    android:drawable="@drawable/btn_default_normal_green" />
<item android:state_focused="true"
    android:drawable="@drawable/btn_default_normal_disable_focused" />
<item
     android:drawable="@drawable/btn_default_normal_disable" />

谁能帮我弄清楚为什么按钮不再遵循这些状态?

谢谢!

【问题讨论】:

    标签: android button listener


    【解决方案1】:

    我认为您的侦听器的 onTouch 方法应该返回 false,否则您只需覆盖在触摸事件上更新可绘制对象的“正常”行为。

    【讨论】:

    • 如果我这样做了,那么我就不会处理 ACTION_UP 事件。按钮更新了,但其他一些东西失败了(仍在努力查看内容)。
    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2013-03-09
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多