【问题标题】:ButtonView with different background不同背景的ButtonView
【发布时间】:2015-09-19 15:04:44
【问题描述】:

我设计了一个圆角按钮。

button_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners android:radius="10dp"/>

</shape>

在布局中:

<Button
   android:background="@drawable/button_selector"
.../>

每次点击时,应该按钮的颜色都会改变:

在活动中,在 onClickListener() 内部:

btn1.setBackgroundColor(getAnswerColor(choiceArray[0]));

但如果我这样做,我不会得到更圆的角落。

如何获得圆角?请提出建议。

【问题讨论】:

  • button_selector.xml 的邮政编码
  • 请检查上面的代码。
  • 请检查答案并给予回复...
  • @megha 如果您必须制作圆角按钮,您可以使用我在回答中提到的工具站点制作。使用该站点制作按钮,复制代码并应用于您的项目。

标签: android android-button rounded-corners


【解决方案1】:

您可以从此工具站点制作按钮 ==> Android Button Maker

你可以用这个工具用代码制作任何类型的按钮。

我在这里根据您的要求编辑此答案。

所以,为不同的背景颜色制作两个不同的按钮,并使用选择器来更改 onClick 的背景。为此,请使用此代码。

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

 <item android:drawable="@drawable/click_button" android:state_pressed="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/not_click_button" android:state_pressed="false" />

</selector>

【讨论】:

  • 任何创建的自定义样式都设置为 ButtonView 的背景。而且在动态改变ButtonView的背景颜色的同时,我还得设置backgroundColor,这反过来又取消了style的效果。
  • 我已经根据您的要求编辑了我的答案,请按照此操作获得您的解决方案。
【解决方案2】:

试试这个方法

我检查了下面的 xml

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

<item >
<shape android:shape="rectangle"  >
     <corners android:radius="13dip" />
     <stroke android:width="1dip" android:color="#5e7974" />
     <gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />            
 </shape>
</item>
</selector>

在按钮上单击添加此代码

  StateListDrawable drawable = (StateListDrawable) v.getBackground();
  drawable.setColorFilter(Color.RED,PorterDuff.Mode.SRC_ATOP);
  button1.setBackground(drawable);

【讨论】:

    【解决方案3】:
    btn1.setBackgroundResource(R.drawable.button_selector);
    
    GradientDrawable drawableGradient = (GradientDrawable) btn1.getBackground();
    drawableGradient .setColor(Color.RED);
    

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2017-06-21
      • 1970-01-01
      相关资源
      最近更新 更多