如何更改(删除然后添加)Android背景中的按钮背景?

时间:2012-09-03 23:18:11

标签: android layout dynamic background

我正在尝试动态更改按钮的background。该按钮已在main.xml中具有归属于它的背景渐变。我试过了:

featuredimage.setBackgroundDrawable(res.getDrawable(R.drawable.black_gradient));

但是得到以下错误:

09-03 23:16:12.279: E/AndroidRuntime(562): FATAL EXCEPTION: main
09-03 23:16:12.279: E/AndroidRuntime(562): java.lang.NullPointerException
09-03 23:16:12.279: E/AndroidRuntime(562):  at My.Taste.App.MyTasteActivity.changeCatagory(MyTasteActivity.java:188)
09-03 23:16:12.279: E/AndroidRuntime(562):  at My.Taste.App.MyTasteActivity.access$0(MyTasteActivity.java:160)
09-03 23:16:12.279: E/AndroidRuntime(562):  at My.Taste.App.MyTasteActivity$8.onClick(MyTasteActivity.java:155)
09-03 23:16:12.279: E/AndroidRuntime(562):  at android.view.View.performClick(View.java:3511)
09-03 23:16:12.279: E/AndroidRuntime(562):  at android.view.View$PerformClick.run(View.java:14105)
09-03 23:16:12.279: E/AndroidRuntime(562):  at android.os.Handler.handleCallback(Handler.java:605)
09-03 23:16:12.279: E/AndroidRuntime(562):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-03 23:16:12.279: E/AndroidRuntime(562):  at android.os.Looper.loop(Looper.java:137)
09-03 23:16:12.279: E/AndroidRuntime(562):  at android.app.ActivityThread.main(ActivityThread.java:4424)
09-03 23:16:12.279: E/AndroidRuntime(562):  at java.lang.reflect.Method.invokeNative(Native Method)
09-03 23:16:12.279: E/AndroidRuntime(562):  at java.lang.reflect.Method.invoke(Method.java:511)
09-03 23:16:12.279: E/AndroidRuntime(562):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-03 23:16:12.279: E/AndroidRuntime(562):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-03 23:16:12.279: E/AndroidRuntime(562):  at dalvik.system.NativeStart.main(Native Method)

是的,black_gradient文件存在。

附加代码:

featuredimage = (ImageView) findViewById(R.id.featuredimage);
featuredinfo = (TextView) findViewById(R.id.featuredinfo);
featuredinfo.setText(Html.fromHtml("<center><big><b>FEATURED " + catagory + "</b></big></center><br>" + getFeatured().getMediumString()));

1 个答案:

答案 0 :(得分:1)

res应该有问题。试试这个:

featuredimage.setBackgroundDrawable(getResources().getDrawable(R.drawable.black_gradient));

您也可以使用android.view.View.setBackgroundResource

  

featuredimage.setBackgroundResource(R.drawable.black_gradient);