0

我有一個DialogFragment彈出來要求用戶選擇選擇拍照,或從圖庫中選擇一個。當我打開圖庫並選擇圖像時,沒有任何反應,OnActivityResult不響應。是否因爲DialogFragment類在圖像被選中後不久就關閉了,並且沒有時間通過​​OnActivityResult類?OnActivityResult不響應DialogFragment

這裏是onCreateDialog爲DialogFragment類:

public class PhotoFragment extends DialogFragment { 


public static final int SELECT_PHOTO = 100; 

public Bitmap image; 


public static interface OnCompleteListener { 
    public abstract void onComplete(Bitmap image); 
} 

@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the Builder class for convenient dialog construction 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    builder.setItems(new CharSequence[] 
        {"Take a Photo", "Select Image From Gallery"}, 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        // The 'which' argument contains the index position 
        // of the selected item 
        switch (which) { 
         case 0: 
          Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
          startActivityForResult(takePicture, 0);//zero can be replaced with any action code 
          break; 
         case 1: 
          doToast("Picking Image",true); 
          Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
          startActivityForResult(pickPhoto , SELECT_PHOTO);//one can be replaced with any action code 
          break; 

        } 
       } 
      }); 
    return builder.create(); 
} 

下面是activityOnResult()的代碼(位於同一個班級,PhotoFragment.java)

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    doToast("Activity Result", true); 
    switch (requestCode) { 
     case SELECT_PHOTO: 

       Uri selectedImage = imageReturnedIntent.getData(); 
      InputStream imageStream = null; 
      try { 
       imageStream = getContext().getContentResolver().openInputStream(imageReturnedIntent.getData()); 
      } catch (FileNotFoundException e) { 
       doToast("Input Stream not found", true); 
       e.printStackTrace(); 
      } 
      Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream); 
      image = yourSelectedImage; 


    } 
} 
+0

其中您在片段類或主要活動中實現了onactivityresult? – Pavan

+0

我嘗試在片段類中執行,並進入活動,迄今爲止沒有工作。 –

回答

0

確保你您的活動中沒有onActivityResult。

+0

我做了,評論它,但它沒有什麼區別。我仍然沒有得到激活的onActivityResult方法:( –

+0

嘗試添加getActivity()。之前startActivityForResult – vguzzi

0

在您的活動中添加onActivityResult,然後獲取片段並調用片段onActivityResult。例如:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); 
    fragment.onActivityResult(requestCode, resultCode, data); 
}