To change the background color, such as buttons,
button.setBackgroundColor (Color.RED);
It can be done in , but if you specify the layout of the button as drawable, the above description is
The drawable specification is disabled (Radius, etc. is ignored and becomes just a red button)
So I got background information from GradientDrawable and tried to change it, but it didn't work
public class MainActivity extensions Activity implements OnClickListener{
@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById (R.id.button).setOnClickListener(this);
}
public void onClick (View view) {
// This disables the drawable specification in the xml file.
// view.setBackgroundColor (Color.RED);
GradientDrawable background=(GradientDrawable) view.getBackground();
background.setColor (Color.RED);
}
}
The button layout described in activity_main.xml looks like this
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android: id="@+id/button"
android:background="@drawable/button_background"/>
drawable's button_background.xml (Round corners, gray).I want to change this color.)
<?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="5dp"/>
<solid android:color="#555555"/>
</shape>
</item>
</selector>
The emu stands up and presses the button to get an error
Which part is wrong?
If possible, I would appreciate it if you could correct the code
Also, the setBackgroundResource (resource) that you answered is fine, but
Is it possible to dynamically change only the drawable file solid android:color="@color/COLORNAME"?
This is what it looks like to control only with Java code.Create Drawable and apply it.In this example, you can change the color_flag value to various colors.
public class MainActivity extensions Activity implements OnClickListener{
Button bt;
int color_flag = 0;
@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.button);
bt.setOnClickListener(this);
}
@ Override
public void onClick (View v) {
GradientDrawable drawable=new GradientDrawable();
drawable.mute();
drawable.setShape(0); //0 is RECTANGLE
drawable.setCornerRadius(5);
if(color_flag==0){
drawable.setColor(Color.parseColor("#FF3300")); // Red
} else if(color_flag==1){
drawable.setColor(Color.parseColor("#0000FF")); // Blue
} else{
drawable.setColor(Color.parseColor("#55555")); // Original color
}
bt.setBackground(drawable);
}
}
© 2024 OneMinuteCode. All rights reserved.