set app background from gallery

半世苍凉 提交于 2019-12-25 08:17:31

问题


I've got an app using shared preferences to set the background from a few pre-determined images, but I'd like to allow the user to be able to pick an image from their gallery. How can I do this?

Code below:

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:


In onCreate method add these lines to pick an image from your gallery:

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

and below onCreate add this method:

@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;
            }
    }
}

Also, add this permission in manifest file:

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


来源:https://stackoverflow.com/questions/10063763/set-app-background-from-gallery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!