简体   繁体   English

单击时更改按钮颜色

[英]Change button color when clicked

OK, when I use setBackground on a button, the button no longer shows any feedback when its clicked. 好的,当我在按钮上使用setBackground时,该按钮在单击时不再显示任何反馈。 How can I fix this. 我怎样才能解决这个问题。 I just want the button to get darker or some type of feedback so the user knows it was clicked. 我只希望按钮变暗或某种类型的反馈,以便用户知道它已被单击。

Hope this makes sense! 希望这有道理!

Create this drawable and bind it to button background 创建此可绘制对象并将其绑定到按钮背景

<selector 
xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
 <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
 <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
 <item android:drawable="@drawable/YOURIMAGE" />
 </selector>

Apply it to button 应用于按钮

android:background="@drawable/button"

You need to create a selector inside the XML and have it linked to state_pressed = "true". 您需要在XML内创建一个选择器,并将其链接到state_pressed =“ true”。 Inside of the item, you can specify the shape of the object. 在项目内部,您可以指定对象的形状。 I've linked to the Android developer site so you can see other options available as well. 我已链接到Android开发者网站,因此您也可以看到其他可用选项。

        <item android:state_pressed="true">
            <shape>
                <solid android:color="#73E5E4D7" />
            </shape>
        </item>
        <item>
            <shape>
                <solid android:color="#E6E5E4D7" />
            </shape>
        </item>

Android Developer State List Android开发者状态列表

hope this works well. 希望这能很好地工作。 first assign your button into a button type reference in your activity class. 首先将您的按钮分配到活动类中的按钮类型引用中。 ex: newBtn=(Button) findViewById(R.id.yourButton); 例如: newBtn=(Button) findViewById(R.id.yourButton);

after that set an listener to that button. 之后,将监听器设置为该按钮。

  yourButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            yourButton.setBackgroundColor(int colorCode);
        }
    });

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

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