我制作了一个包含按钮的应用程序。此按钮会将我们带到手机的图库,用户可以在其中选择任何图像,该图像将显示在按钮下方的应用程序中。现在我想要一个按钮,将该图像设置为壁纸,我需要保存按钮的代码。 这是代码。
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private static int LOAD_IMAGE_RESULT = 1;
Button b1,b2;
ImageView IV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
IV = (ImageView)findViewById(R.id.imageView);
b2 = (Button)findViewById(R.id.save);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == LOAD_IMAGE_RESULT && resultCode == RESULT_OK && data != null){
Uri pick = data.getData();
String[] images = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pick,images,null,null,null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(images[0]));
IV.setImageBitmap(BitmapFactory.decodeFile(imagePath));
cursor.close();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, LOAD_IMAGE_RESULT);
break;
case R.id.save:
break;
}
}
}
答案 0 :(得分:1)
如果我错了,我不确定我是否理解你的问题是正确的。您想将所选图像设置为墙纸。
WallpaperManager wManager = WallpaperManager.getInstance(getApplicationContext());
try {
wManager.setBitmap(BitmapFactory.decodeFile(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
最后,您需要此权限:
<uses-permission android:name="android.permission.SET_WALLPAPER">