我想在我的应用程序中使用功能,用户可以从手机内存中选择背景(.png/.jpg
文件)。我猜80%的任务已经通过这个链接完成http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/如何在Android中设置自定义背景?
上面链接的代码只是显示了SD卡的视图,现在我想设置任何图像文件作为我的应用程序背景。我怎样才能做到这一点?
我想在我的应用程序中使用功能,用户可以从手机内存中选择背景(.png/.jpg
文件)。我猜80%的任务已经通过这个链接完成http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/如何在Android中设置自定义背景?
上面链接的代码只是显示了SD卡的视图,现在我想设置任何图像文件作为我的应用程序背景。我怎样才能做到这一点?
如果你想只需选择图像并设置背景,我觉得simpliest方式是这样的:
.....
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PICTURE_ACTIVITY_REQUEST_CODE);
....
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PICTURE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
setBackgroundDrawable(new BitmapDrawable(bitmap));
}
cursor.close();
}
break;
}
}
看看我对a.ch的回答的评论。我认为你接近解决。 – mrana 2012-02-27 10:43:55
根据您的应用程序,每个现有布局周围都有一个FrameLayout,以适当设置的ImageView开始。
如果你想要做你的活动parentview动态使用
setBackgroundColor(int color)
或
setBackgroundResource(int resourceID)
。
对不起,但我指出的东西并不是那么容易,你可能会想到。 – mrana 2012-02-27 10:27:17
宥可以试试这个:
Bitmap srcBitmap = BitmapFactory.decodeStream(new FileInputStream(new File("path/to/file.jpg")));
BitmapDrawable bmpDrawable = new BitmapDrawable(srcBitmap);
YourView.setBackgroundDrawable(bmpDrawable);
我想你的问题是你不知道如何加载从画廊中挑选的图像。 @ appserv的答案可以解决你的问题,但是如果你需要从任何来源(包括你的应用程序资源)加载图片,看看它是如何的implemented in ImageView
其实我创建了一个名为setBackground的菜单项,点击后会打开一个对话框,其中包含两个按钮1.设置自定义背景2.默认背景。当用户首先点击手机存储器loc或SDCarddir(无论什么)应该打开,然后用户可以选择存在的图片现在应用程序应该有新的背景,也可以通过使用第二个按钮用户可以切换到默认的背景。 – mrana 2012-02-27 10:36:29
这正是appserv的解决方案所做的,除了恢复默认背景。将与'startActivityForResult(..)'相关的代码放入'onContextItemSelected(..)'方法中。 – 2012-02-27 10:56:08
谢谢,但问题是谁应该得到信用? :)你或appserv – mrana 2012-02-27 11:02:12
其实,为了得到正确的你们必须遵循两个答案,一个是appserv的答案我选择了,但为了确切的解决方案,看看我和a.ch之间的对话... – mrana 2012-02-27 11:07:57