Android 单击视觉状态更改的按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10425741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:41:48  来源:igfitidea点击:

Button on click visual state change

androidformsanimationbutton

提问by marchemike

Is there any way to animate a button in Android so that when you click it it changes the background of the button to a pressed image?

有什么方法可以在 Android 中为按钮设置动画,以便在单击它时将按钮的背景更改为按下的图像?

I'm only using the background property to show the image on the form button.

我只使用背景属性在表单按钮上显示图像。

回答by Krishnakant Dalal

Use this XML: save it in drawable folder and set as the background drawable.

使用此 XML:将其保存在 drawable 文件夹中并设置为背景可绘制。

<?xml version="1.0" encoding="utf-8" ?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/category_listing_bg_img" /> 
<item android:state_pressed="true" android:drawable="@drawable/category_listing_bg_img_pressed" /> 
</selector>

回答by K_Anas

add an xml file on your res/drawable folder name it button_selector.xml put also two drawable one for the pressed state and onother for unpressed or normal state. Finally add this two your xml file button selector and everything should work!! don't forget to set the @drawable/bytton_selector.xml as the background of your button on your main.xml file.

在 res/drawable 文件夹中添加一个 xml 文件,将其命名为 button_selector.xml 还放置了两个可绘制的,一个用于按下状态,另一个用于未按下或正常状态。最后添加这两个您的 xml 文件按钮选择器,一切正常!不要忘记将 @drawable/bytton_selector.xml 设置为 main.xml 文件中按钮的背景。

  <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">

     <item android:drawable="@drawable/btn_pressed" android:state_pressed="true"/>
       <item android:drawable="@drawable/btn_unpressed"/>

  </selector>

回答by drulabs

Yes there is. Implement onTouchListener. use the MotionEvent variable (lets say event) in onTouch method write this:

就在这里。实现 onTouchListener。在 onTouch 方法中使用 MotionEvent 变量(让我们说事件)写这个:

if (event.getAction() == MotionEvent.ACTION_DOWN){
    /*Code*/
}
if (event.getAction() == MotionEvent.ACTION_UP){
    /*Code*/
}

回答by thepoosh

what you should do is create a selector(what Krishnakant Dalal was talking about). it handels how the UI element looks like at every single state it can be (presses, disabled, normal etc.)

您应该做的是创建一个selector(Krishnakant Dalal 所说的)。它处理 UI 元素在每个状态(按下、禁用、正常等)下的外观

for more about selectors read here: http://android-journey.blogspot.com/2009/12/android-selectors.html

有关选择器的更多信息,请阅读此处:http: //android-journey.blogspot.com/2009/12/android-selectors.html