我想在Android中将纯色设置为壁纸,但是当我点击按钮时,应用程序很快停止了。
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WallpaperManager wm = WallpaperManager.getInstance(getApplicationContext());
try {
wm.setResource(R.color.red);
Toast.makeText(getApplicationContext(), "Wallpaper changed", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
这是colors.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff4366</color>
</resources>
logcat的:
10-24 15:59:26.216 12529-12529/com.danish.testapp D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
10-24 15:59:26.216 12529-12529/com.danish.testapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.danish.testapp, PID: 12529
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
at android.content.res.Resources.openRawResource(Resources.java:1271)
at android.content.res.Resources.openRawResource(Resources.java:1241)
at android.app.WallpaperManager.setResource(WallpaperManager.java:739)
at com.danish.testapp.MainActivity$1.onClick(MainActivity.java:30)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我还在清单中设置了所需的权限。
答案 0 :(得分:2)
对于WallpaperManager,您必须设置drawable。
devise
被修改
您也必须设置权限。
wm.setResource(R.drawable.your_drawable);
对于可绘制的设置颜色,您可以使用
android.permission.SET_WALLPAPER
被修改
最后解决:
我写一个样本。有效。享受它。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/your_coloe" />
</shape>
</item>
</selector>