onTouchListener覆盖Button视图上的自定义背景?

Jas*_*son 3 android state background view

我的res/drawable文件夹中有一个button_animation.xml,用于显示不同的按钮状态(默认,按下,聚焦).我在布局文件的按钮中引用了button_animation.xml.它完美地工作,除了我在实际被按下的按钮上设置onTouchListener.以下是我的代码.

button_animation.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_default" />
</selector>
Run Code Online (Sandbox Code Playgroud)

layout.xml

     <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:background="@drawable/button_animation" />
Run Code Online (Sandbox Code Playgroud)

导致动画中断的代码

Button button = (Button) findViewById(R.id.button1);
button.setOnTouchListener(this);
Run Code Online (Sandbox Code Playgroud)

我是否无法按照文档建议显示按钮状态并同时处理任何特定视图的onClick?

文档:http://developer.android.com/guide/topics/ui/controls/button.html

谢谢,

贾森

Esh*_*aan 7

这个答案很老了,但万一有人来搜索如何做到这一点,以下是你如何做到这一点.@Shadesblade很接近,但并不完全.

public boolean onTouch(View button, MotionEvent theMotion) {

    switch (theMotion.getAction()) {

      case MotionEvent.ACTION_DOWN: 
          button.setPressed(true);
          break;
      case MotionEvent.ACTION_UP: 
          button.setPressed(false);
          break;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以使用xml选择器drawable并仍然使用ontouchlistener切换状态.

还要确保视图"按钮"是可点击的(默认情况下可以单击按钮类,但如果您使用的是其他视图/视图组,则需要在xml中对其进行delcare).