繁体   English   中英

将按钮背景更改为单击

[英]Change button background to clicked

当您在Android中按下按钮时,它会更改颜色。 我希望它保持那样。 我的意思是我想要这样的东西:

Button btn = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             btn.setBackGroundColor(R.drawable.clicked /*clicked style*/ );
         }
     });

例:

在此处输入图片说明

这是一个按下的按钮。 我希望它在停止按下后保持这种状态。 有没有像这样的简单方法:

android.R.drawable.btn_default //这是默认的按钮样式,我要按一个:D

在您的Java代码中编写button.setPressed(true); 。它将按钮设置为按下模式。 要将参数设置为按下和未按下,可以将参数更改为true和false。

因此,您希望它不被按下就开始,然后在被点击后保持按下状态吗? 尝试使用OnTouchListener代替添加btn.setPressed(true);

public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                btn.setPressed(true);
            }
            return true;
        }

尝试使用选择器:

在可绘制文件夹中定义selector.xml

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

并将按钮的背景设置为android:background="@drawable/selector"然后在按钮click事件的代码中设置btn.setpressed(true);

您可以尝试通过这种方式尝试将图像按为深色或按彩色

drawable / selector.xml

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

在内部创建方法中写入

btn.setBackgroundResource(R.drawable.selector);

看看StateSelector图像

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

您可以为按钮/视图的不同状态设置不同的资源。 本示例设置了不同的颜色:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">    
    <item android:drawable="@color/branded_content_pressed_color" android:state_enabled="true" android:state_pressed="true"/>
    <item android:drawable="@color/branded_content_pressed_color" android:state_enabled="true" android:state_focused="true"/>
    <item android:drawable="@color/branded_content_background_color"/>
</selector>

然后您可以正常设置选择器

button.setBackgroundResource(R.drawable.selector);

暂无
暂无

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

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