我试图这样做:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && 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();
Bitmap bmp = BitmapFactory.decodeFile(picturePath);
b[1].setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bmp), null, null);
}
但它不会设置图像,无论如何。我也尝试了几种不同的方法,比如使用图像按钮代替按钮并使用:
imageButton.setImageBitmap(bmp)
图库打开正常,回调来到onActivityResult(...) 但是图像不会出现在按钮上,我有一系列按钮。
答案 0 :(得分:0)
我做了一个快速测试。以下代码适用于我。如果使用此功能,您仍然无法设置图像,我会检查是否存在布局问题(即图像已设置但没有显示空间)。
activity_main.xml只有一个ImageButton设置为wrap_content,在主布局中是match_parent。
public class MainActivity extends Activity {
ImageButton imgButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_CANCELED) return;
ParcelFileDescriptor fd;
try {
fd = getContentResolver().openFileDescriptor(data.getData(), "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
Bitmap bmp = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
imgButton.setImageBitmap(bmp);
}
}