我是Android编程的新手,我正在创建一个具有按钮和ImageView的应用程序。只有一个ImageView,其中的图像根据用户的选择动态变化。现在我要做的是当用户点击按钮时,图像成为手机的壁纸。这是我试过的两个代码,但当它成为壁纸时,它只是一个小部分作为壁纸非常大。首先我尝试了这个:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int resID = getResources().getIdentifier(imageName, "drawable", getPackageName());
WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
try {
wpm.setResource(resID);
Toast.makeText(MainActivity.this,
"Wallpaper successfully changed", Toast.LENGTH_SHORT)
.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
我尝试和替换的第二个是:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int resID = getResources().getIdentifier(imageName, "drawable", getPackageName());
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Bitmap tempbitMap = BitmapFactory.decodeResource(getResources(), resID);
Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
wallpaperManager.setWallpaperOffsetSteps(1, 1);
wallpaperManager.suggestDesiredDimensions(width, height);
try {
wallpaperManager.setBitmap(bitmap);
Toast.makeText(MainActivity.this,
"Wallpaper successfully changed", Toast.LENGTH_SHORT)
.show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
我还在AndroidManifest中添加了这两个权限:
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" /
>
我不知道问题出在哪里。 Plz帮助