[英]Changing Image Button with a Gallery Image in Android
我到處尋找以下問題的解決方案,但未發現任何問題。 在應用程序中,我有一個帶有預定義可繪制對象的ImageButton。 我要做的就是讓用戶單擊此ImageButton,從手機的圖像庫中選擇一張圖片並顯示該圖片,直到用戶再次更改它為止。 到目前為止,我設法顯示了ImageGallery並可以選擇圖片,但是我無法執行以下操作:
1. Show the Picture from the Picture Gallery in the shape of the original drawable -- it is a circle
2. When I change activity and come back to this activity, the picture chosen is not there anymore.
我的代碼如下所示:ImageButton的XML在LinearLayout中
<ImageButton
android:id="@+id/AddPic"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:background="#00FFFFFF"
android:contentDescription="@string/MyInformation"
android:gravity="left"
android:onClick="AddPic"
android:src="@drawable/dp_holder_large"
/>
我的Java代碼如下所示:
public class MyInformation extends Activity{
ImageButton imgButton;
public static int RESULT_LOAD_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myinformation);
//Adding the picture bit
imgButton = (ImageButton) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(GaleryIntent, RESULT_LOAD_IMAGE);
}
});
}
@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 SelectedCursor = getContentResolver().query(SelectedImage, FilePathColumn, null, null, null);
SelectedCursor.moveToFirst();
int columnIndex = SelectedCursor.getColumnIndex(FilePathColumn[0]);
String picturePath = SelectedCursor.getString(columnIndex);
SelectedCursor.close();
// Drawable d = new BitmapDrawable(getResources(),BitmapFactory.decodeFile(picturePath));
// btnOpenGalery .setImageBitmap(d);
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Toast.makeText(getApplicationContext(), picturePath, Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
謝謝!
問題1的解決方案:
刪除背景並使用圓圈制作自定義背景。
不要使用android:src="@drawable/dp_holder_large"
因為一旦您將圖像設置好,圓圈就會消失
問題2的解決方案:
您需要使用startActivityForResult()
方法調用新活動
Intent newIntent = new Intent(CurrentActivity.this, NextActivity.class);
startActivityForResult(newIntent, 2);
並在您的onActivityResult()
方法中執行
if(resultCode==2){
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));//where picturePath is the path
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.