如何在ImageView中多次更改图像?

时间:2011-11-23 05:54:47

标签: android imageview gallery

我的应用程序将您的图库中的照片添加到ImageView中,但如果我尝试更改图像(在选择了一个图像之后),我的应用程序强制关闭。有没有办法实现这个目标?

这是我的代码..

private static final int SELECT_PICTURE = 1;

private String selectedImagePath;
private ImageView img;

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

    img = (ImageView)findViewById(R.id.myimageview);

    ((Button) findViewById(R.id.taptoadd))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
                }
            });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }
   }
}

public String getPath(Uri uri) {
   String[] projection = { MediaStore.Images.Media.DATA };

    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);


}

}

1 个答案:

答案 0 :(得分:1)

通过代码设置图像。

ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);