[英]OnActivityResult called before OnClick
我試圖創建一個意圖來打開圖庫(效果很好)。
但是,我需要更改圖像按鈕以顯示用戶選擇的圖片的圖像。
問題在於,在galleryIntent()方法之前調用了onActivityResult()方法,這導致結果代碼不是RESULT_OK,因此,當選擇圖片時,用戶將重定向到應用程序,並且什么也沒有發生。
public class DataEntryActivity extends AppCompatActivity {
ImageButton imgButton;
Bitmap bmp;
private static final int PICTURE_SELECTED = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.bernine.practicalsessions.R.layout.activity_portal);
imgButton = (ImageButton) findViewById(com.example.bernine.practicalsessions.R.id.imageButton1);
}
//Method to start the intent upon clicking the imageButton
public void galleryIntent(View view) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, PICTURE_SELECTED);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(getApplicationContext(), "Image Opened Before", Toast.LENGTH_LONG).show();
if (resultCode == RESULT_OK) {
try {
InputStream stream = getContentResolver().openInputStream(data.getData());
bmp = BitmapFactory.decodeStream(stream);
stream.close();
Toast.makeText(getApplicationContext(), "Image Opened", Toast.LENGTH_LONG).show();
imgButton.setImageBitmap(bmp);
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Could not open file.", Toast.LENGTH_LONG).show();
}
}else
{
Toast.makeText(getApplicationContext(), "Result not ok", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
我嘗試在清單中的活動中執行android:launchMode =“ standard”,但沒有用。
您不必啟動新的圖片選擇任務-
public void galleryIntent(View view) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
**//Remove this line**
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, PICTURE_SELECTED);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.