我在实现一个简单的方法来添加一个 Button
到 LinearLayout
程式化。
当我调用setBackground(Drawable background)方法时,出现了以下情况。Error
是抛出的。
java.lang.NoSuchMethodError: android.widget.Button.setBackground
我的addNewButton方法
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);
}
你可能在低于16级的API上进行测试 (果冻豆).
该 设置背景 方法只在该API级别以上可用。
我可以尝试用 setBackgroundDrawable 或 setBackgroundResource 如果是这样的话。
比如说
Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
Button one = new Button(this);
// mediocre
one.setBackgroundDrawable(d);
Button two = new Button(this);
// better
two.setBackgroundResource(R.drawable.ic_launcher);
要为View创建一个均匀的背景,你可以创建一个shape类型的可绘制资源,并使用setBackgroundResource.
red_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF0000"/>
</shape>
活动。
Button b = (Button)findViewById(R.id.myButton);
b.setBackgroundResource(R.drawable.red_background);
但这看起来会很糟糕,平坦而不合适。如果你想要一个看起来像按钮的彩色按钮,你可以自己设计(圆角、描边、渐变填充......)或者一个快速而肮脏的解决方案是给按钮的背景添加一个PorterDuff过滤器。
Button b = (Button)findViewById(R.id.myButton);
PorterDuffColorFilter redFilter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
b.getBackground().setColorFilter(redFilter);
因为在Android 16之后,setBackgroundDrawable被废弃了,我建议在设置代码之前先检查一下。
你也需要检查当前的Android版本
Button bProfile; // your Button
Bitmap bitmap; // your bitmap
if(android.os.Build.VERSION.SDK_INT < 16) {
bProfile.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));
}
else {
bProfile.setBackground(new BitmapDrawable(getResources(),bitmap));
}
<Button
android:id="@+id/btnregister"
android:layout_width="150dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="20dp"
android:paddingVertical="5dp"
style="@style/btn_register"
android:text="Register"
android:textColor="#FFFFFF" />
在Styles.xml文件中应用以下代码。
<style name="btn_register">
<item name="android:layout_marginTop">15dp</item>
<item name="android:backgroundTint">#009688</item>
<item name="cornerRadius">20dp</item>
</style>
你不能使用 setBackground()
.这个方法可能在你的Android级别中不可用。