Button.setBackground(Drawable background)抛出NoSuchMethodError

Esl*_*med 11 java android exception button

我正在实现一个简单的方法来ButtonLinearLayout编程方式添加一个.

当我调用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);
}
Run Code Online (Sandbox Code Playgroud)

Men*_*ena 36

您可能正在测试16级以下的API(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);
Run Code Online (Sandbox Code Playgroud)