【问题标题】:How to change the background color of a clicked button in android when background tint attribute is default in button?当背景色调属性在按钮中为默认值时,如何更改android中单击按钮的背景颜色?
【发布时间】:2021-07-01 16:43:57
【问题描述】:
      These are the attributes I have used in this button.
        I have also created one XML file button_round_corner_view.
           
           <Button
                        android:id="@+id/true_button"
                        android:layout_width="90dp"
                        android:layout_height="50dp"
                        android:layout_margin="10dp"
                        android:background="@drawable/button_round_corner_view"
                        android:padding="10dp"
                        android:text="True"
                        android:textColor="#000000"
                        android:textStyle="bold"
                        app:backgroundTint="#F8F4F4"
                        />
                
    This is the XML file attribute that I have created for a better button look.
please provide me the best answer for this problem and also tell me how to stop 

按钮默认应用的背景色属性

   <?xml version="1.0" encoding="utf-8"?>
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
        
            <corners
                android:radius="20dp"/>
        
            <!-- This is the border color -->
            <stroke
                android:width="2dp"
                android:color="@color/purple_700"/> 
      
            <!-- This is the background color -->
            <solid
                android:color="@color/white"/> 

        </shape>
                                                   

按钮中的BackgroundTint 属性是默认值。我想在用户单击按钮时更改按钮的背景颜色。 如何实现这一点。请帮帮我。

【问题讨论】:

  • 您想在用户触碰按钮时更改颜色以获得某些效果?
  • 例如,当用户点击真假按钮并且答案是对还是错时,根据正确答案的情况我想将按钮背景颜色更改为绿色,而对于错误答案我想将按钮背景颜色更改为红色
  • 背景色属性为默认
  • 好的,我知道了,让我写代码并在答案中发布

标签: java android-studio button onclick background-color


【解决方案1】:

例如让我们说button1,所以它会像

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Answer.equals("Correct")){
                button1.setBackgroundColor(mContext.getResources().getColor(R.color.DarkGreen));
                
            }else if(Answer.equals("InCorrect")){
                button1.setBackgroundColor(mContext.getResources().getColor(R.color.red));
            }
                
            }
        });

你可以做这样的事情。这就是改变按钮颜色的方式。

【讨论】:

  • 你迟到了,我昨天得到了答案,简单的解决方案将按钮的 backgroundTint 属性值设置为 ="@null" 并像您在上面写的那样放置 if else 条件,因此情况如此解决了。感谢您抽出宝贵时间。
  • 我已经使用了get drawable的设置背景属性,并且我还在drawable目录中创建了xml文件。我的解决方案和你的不同。
  • 哦,很高兴知道这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
相关资源
最近更新 更多