简体   繁体   English

将ImageButton的图像更改为来自Gallery Android的图像

[英]Change Image of an ImageButton into an Image from Gallery Android

So in mainactivity, I have an imageview changed to a picture from gallery. 因此,在mainactivity中,我将imageview更改为图库中的图片。 I want to change the image of an ImageButton in another activity into the picture that was selected. 我想将另一个活动中的ImageButton的图像更改为所选的图片。

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() 然后使用SharedPreferences获取imagePath并将图像加载到anotherActivity()

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)));

}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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