Android的如何通过编程设置按键行程和半径 [英] Android how to programmatically set Button stroke and radius
问题描述
我有48 按钮这一活动
,用户可以触摸和更改文字和背景颜色。
I have this activity with 48 Button
that the user can touch and change text and background color.
但是,当用户改变背景颜色,我有这种坏的结果
这是XML的那种风格的dafault 按钮
These are the xmls that style the dafault Buttons
buttons.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused"
android:state_focused="true" />
<item android:drawable="@drawable/button_default" />
</selector>
button_default.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="100dp"
/>
<solid
android:color="#FFFFFF"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<stroke
android:width="3dp"
android:color="#787878"
/>
</shape>
在其他XML只更改颜色,所以我尽量避免张贴他们。
这里是code,它编程方式更改按钮。
我从 DB
一切都改变了按钮
保存 ID
和设置按钮的颜色
。
In the other xml change only the color so i avoid to post them.
And here is the code that change the Button
programmatically.
I take from DB
all changed Button
saved with ID
and set the color of the Button
.
//Get all materie inside database
List<Materia> materia = db.getAllMaterie();
//change all TextView inputed from user
if(materia.isEmpty()){
//do nothing
}else {
for (Materia mat : materia) {
//Change all the Button with values stored inside the database
int resId = getResources().getIdentifier(mat.getID(), "id", getPackageName());
final Button changedButton = (Button) findViewById(resId);
changedButton.setText(mat.getMateria());
changedButton.setTypeface(null, Typeface.BOLD);
changedButton.setBackgroundColor(mat.getColor());
}
}
但我失去半径和中风财产。
有一些方法来设置他们编程?
其他的建议被接受!
推荐答案
我的问题解决了这一行code的
I solved the problem with this line of code
changedButton.getBackground().setColorFilter(mat.getColor(), PorterDuff.Mode.MULTIPLY);
而不是
changedButton.setBackgroundColor(mat.getColor());
我找回了我的默认按钮
与背景的getBackground()
后,我设定的色彩搭配 setColorFilter(INT,模式);
I get back the background of the my default Button
with getBackground()
and after i set the color with setColorFilter(int, mode);
所以结果成为
//Get all materie inside database
List<Materia> materia = db.getAllMaterie();
//change all TextView inputed from user
if(materia.isEmpty()){
//do nothing
}else {
for (Materia mat : materia) {
//Change all the Button with values stored inside the database
int resId = getResources().getIdentifier(mat.getID(), "id", getPackageName());
final Button changedButton = (Button) findViewById(resId);
changedButton.setText(mat.getMateria());
changedButton.setTypeface(null, Typeface.BOLD);
changedButton.getBackground().setColorFilter(mat.getColor(), PorterDuff.Mode.MULTIPLY);
}
}
这篇关于Android的如何通过编程设置按键行程和半径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!