2013-09-01 64 views
11

我實現一個簡單的方法來添加一個ButtonLinearLayout編程。Button.setBackground(可繪製背景)拋出的NoSuchMethodError

當我調用的setBackground(可繪製背景)方法,下面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); 
} 

回答

29

你可能在API進行測試低於16級(Jelly Bean)。

setBackground方法只能從起該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); 
+0

那麼,什麼是添加解決方案按鈕的背景編程方式低於Api 16..withou t setBackGroundDrawable ..這是不贊同......? –

+1

@EslamYousefMohammed編輯我的回答:嘗試'setBackgroundResource'。 – Mena

+0

我已經設置安卓的minSdkVersion =「9」在我的清單,爲什麼犯規蝕提醒我有關? – wutzebaer

-1

不能使用setBackground()。 這種方法可能在你的Android級別不可用。

+0

FYI:在其當前形式中,這更是一個[註釋](http://stackoverflow.com/help/privileges/comment)比一個答案。 (這可能是爲什麼它被拒絕投票)。 「答案」還應該包括解決問題的可能替代方案,[正如接受的答案](http://stackoverflow.com/a/18559344/104223)。參見[答案]。 – Leigh

1

要創建View的同質背景,您可以創建一個類型爲shape的drawable資源,並將其與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); 
0

由於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)); 
}