gpt4 book ai didi

android - onTouchListener 覆盖按钮 View 上的自定义背景?

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:07 24 4
gpt4 key购买 nike

我的 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>

layout.xml

     <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_animation" />

导致动画中断的代码

Button button = (Button) findViewById(R.id.button1);
button.setOnTouchListener(this);

我是否无法像文档建议的那样显示按钮状态并同时为任何特定 View 处理 onClick?

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

谢谢,

杰森

最佳答案

这个答案已经很老了,但为了以防万一有人来寻找如何做到这一点,这里是你如何做到的。 @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;
}

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

还要确保 View “按钮”是可点击的(按钮类默认情况下是可点击的,但如果您使用其他 View / View 组,则需要在 xml 中删除它)。

关于android - onTouchListener 覆盖按钮 View 上的自定义背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18177489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com