Android 如何以编程方式添加按钮可绘制颜色
可能重复:Android 如何以编程方式添加按钮可绘制颜色,android,Android,可能重复: 我已经在程序中动态添加了表行,并添加了按钮,但按钮的颜色没有改变。我添加了一个XML文件,用于为名为redbtn的按钮添加颜色,当我在“活动”中添加它们时,它会工作,但当我以编程方式添加按钮样式时,颜色不会改变。我能做什么 redbtn.xml <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_pressed="true">
我已经在程序中动态添加了表行,并添加了按钮,但按钮的颜色没有改变。我添加了一个XML文件,用于为名为redbtn的按钮添加颜色,当我在“活动”中添加它们时,它会工作,但当我以编程方式添加按钮样式时,颜色不会改变。我能做什么 redbtn.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true">
<shape>
<solid android:color="#DF0101" />
<stroke android:width="1dp" android:color="#ef4444" />
<corners android:radius="3dp" />
<padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient android:startColor="#DF0101" android:endColor="#DF0101" android:angle="270" />
<stroke android:width="1dp" android:color="#992f2f" />
<corners android:radius="3dp" />
<padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
</shape>
</item>
</selector>
尝试以下操作(如果要将图片添加到背景中):
如果您想尝试,那么您可以在和十六进制代码中以编程方式提供颜色,如下所述
Deletecomponentbtn.setBackgroundColor(Color.parseColor("HexCode"));
(vatsalshah.co.in)setBackgroundColor采用颜色值(argb,int),R.drawable.redbtn为资源ID(int) 这是行不通的 如果你想从资源中应用背景,并且你有它的ID,你应该使用setBackgroundResource(intresid)它可以工作
Deletecomponentbtn.setForeground(Color.GREEN);
Deletecomponentbtn.setBackground(Color.GREEN);
如果您使用hexcode
Deletecomponentbtn.setForeground(Color.parseColor("oxff00ff00"));
Deletecomponentbtn.setBackground(Color.parseColor("oxff00ff00"));
使用这个,
Deletecomponentbtn.setBackgroundResource(R.drawable.redbtn);
Deletecomponentbtn.setBackgroundColor(R.drawable.redbtn);
而不是,
Deletecomponentbtn.setBackgroundResource(R.drawable.redbtn);
Deletecomponentbtn.setBackgroundColor(R.drawable.redbtn);
谢谢。使用
Deletecomponentbtn.setBackgroundResource(R.drawable.redbtn);
并且可以使用按钮的不同状态更正redbtn.xml。nope在我尝试此操作时给出错误,要求将setBackground更改为setBackgroundColorDeletecomponentbtn.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.redbtn));其工作原理请检查编辑的答案。Deletecomponentbtn.setBackgroundColor(getApplicationContext().getResources().getColor(R.drawable.redbtn));这是rightDeletecomponentbtn.setBackgroundColor(getApplicationContext().getResources().getColor(R.drawable.redbtn));也不工作DeleteComponentBTN.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.redbtn));如果我的答案能帮助你解决问题,那么你可以接受。谢谢
Deletecomponentbtn.setBackgroundResource(R.drawable.redbtn);