我正在尝试更改按钮的背景,当用户在模拟器中按下它时一切正常但在真实设备上应用程序崩溃。 这是我的代码:
answerOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
answerOne.setBackgroundResource(R.drawable.button_background_green);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ValidateAnswer(current5,Answers_six[0]);
}
});
并且日志中的错误是:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nasrf.winners10, PID: 9715
android.content.res.Resources$NotFoundException: Resource ID #0x7f080060
at android.content.res.Resources.getValue(Resources.java:1416)
at android.content.res.Resources.getDrawable(Resources.java:861)
at android.content.Context.getDrawable(Context.java:402)
at android.view.View.setBackgroundResource(View.java:16423)
at android.support.v7.widget.AppCompatButton.setBackgroundResource(AppCompatButton.java:83)
at com.example.nasrf.winners10.Game.GameActivity$16.onClick(GameActivity.java:426)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20101)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
有什么帮助吗?
答案 0 :(得分:1)
由于您的模拟器和真实设备的SDK不同而发生了这种情况。
您可以先检查sdk,然后像这样设置背景 -
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
answerOne.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_background_green));
}
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
answerOne.setBackground(getResources().getDrawable(R.drawable.button_background_green));
} else{
answerOne.setBackground(ContextCompat.getDrawable(this, R.drawable.button_background_green));
}