简体   繁体   中英

Change Image of an ImageButton into an Image from Gallery Android

So in mainactivity, I have an imageview changed to a picture from gallery. I want to change the image of an ImageButton in another activity into the picture that was selected.

MainActivity:

private static int RESULT_LOAD_IMAGE = 1;
private final String FILEPATH = "FilePath";

SharedPreferences prefs;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);        

    Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, 1);
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        prefs.edit().putString(FILEPATH, picturePath);

    }


}

Then use SharedPreferences to get the imagePath and load the image in anotherActivity()

anotherActivity() :

public class anotherActivity extends MainActivity{

private final String FILEPATH = "FinalPath";
String path;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstance);
    setContentView(R.layout.main);

    path = prefs.getString(FILEPATH, "");

    ImageButton imageButton = (ImageView) findViewById(R.id.imgBtn);
    imageButton.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(path)));

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM