I'm implementing a simple method to add a Button
to a LinearLayout
programatically.
When I invoke the setBackground(Drawable background) method, the following Error
is thrown:
java.lang.NoSuchMethodError: android.widget.Button.setBackground
My addNewButton method:
private void addNewButton(Integer id, String name) {
Button b = new Button(this);
b.setId(id);
b.setText(name);
b.setTextColor(color.white);
b.setBackground(this.getResources().getDrawable(R.drawable.orange_dot));
//llPageIndicator is the Linear Layout.
llPageIndicator.addView(b);
}
To create a homogeneous background for a View, you can create a drawable resource of type shape, and use that with the setBackgroundResource.
red_background.xml
Activity:
But this will look pretty bad, flat and out of place. If you want a colored button that looks like a button, than you can either design it yourself (rounded corners, stroke, gradient fill...) or a fast and dirty solution is to add a PorterDuff filter to the button's background:
You might be testing on an API below level 16 (Jelly Bean).
The setBackground method is only available from that API level onwards.
I would try with setBackgroundDrawable (deprecated) or setBackgroundResource if that's the case.
For instance:
Since after Android 16 , the setBackgroundDrawable is deprecated, I suggested to checked before set code
you need to check current version of Android also
You can't use
setBackground()
. This method may be not available in your Android level.