从图库设置应用背景

时间:2012-04-08 14:59:43

标签: android background gallery sharedpreferences

我有一个使用共享首选项的应用程序来设置几个预定图像的背景,但我想让用户能够从他们的图库中选择一个图像。我怎样才能做到这一点?

以下代码:

int bak;
int em;
int lo;
int lay;
SharedPreferences data;
public static String filename = "bg";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    lo = R.layout.main;
    data = getSharedPreferences(filename, 0);
    lay = data.getInt("lout", lo);          
    setContentView(lay);

    em = R.drawable.bakgrund;
    data = getSharedPreferences(filename, 0);
    bak = data.getInt("bakgrund", em);

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    RelativeLayout bg = (RelativeLayout) findViewById(R.id.might);
    bg.setBackgroundResource(bak);

1 个答案:

答案 0 :(得分:2)

在onCreate方法中添加以下行以从图库中选择图像:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);

及以下onCreate添加此方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 0:
            data.getDataString()
            if (resultCode == RESULT_OK) {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(_activity.getContentResolver(), data.getDataString());
                    RelativeLayout bg = (RelativeLayout) findViewById(R.id.might);
                    Drawable drawable = new BitmapDrawable(getResources(), bitmap);
                    bg.setBackgroundDrawable(drawable);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
    }
}

此外,在清单文件中添加此权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />