简体   繁体   English

单击后如何更改按钮,释放按钮后又如何恢复正常?

[英]How to change the button upon click ,and revert back to normal upon release the button?

I want my image to change the image as long as i press and hold on to the button . 只要按住按钮,我就想更改图像。 And when i release my finer i want it to revert back to the original image , is there a way to do this ? 当我发布更好的图片时,我希望它还原为原始图像,有没有办法做到这一点?

   bTen.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               bTen.setBackgroundResource(R.drawable.press);
               s1+="E";
               txtView.setText(s1);
           }
       }); 

i have used the above code ,but it does not revert back to original when i release my finger. 我已经使用了上面的代码,但是当我松开手指时它并没有恢复为原始代码。

You should create your own selector and add it as style for your button (in xml) example: 您应该创建自己的选择器,并将其添加为按钮样式(在xml中)的示例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- disabled -->        
    <item android:drawable="@color/..." android:state_enabled="false"/>
 <!-- pressed -->
    <item android:drawable="@color/..." android:state_pressed="true"/>
 <!-- default -->
    <item android:drawable="@color/..."></item>


</selector>

Create a xml in your drawable folder with name of image.xml with this 使用以下命令在您的可绘制文件夹中创建一个名为image.xml的xml。

    <?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/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

Then use this image.xml in your layout xml as 然后在您的布局xml中使用此image.xml作为

           <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="12dp"
    android:background="@drawable/image"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM