在活动A中,我想打开一个对话框(CustomDialog)。在CustomDialog内部,它具有一个打开照相机的按钮。但是在我从图库中选取图片后,onActivityResult
没有得到调用。没有显示toast
。
活动A
private void openDialog() {
CustomDialog alert = new CustomDialog();
alert.showDialog(this);
}
CustomDialog
public class CustomDialog extends Activity{
Activity activity;
ImageView imageView;
public void showDialog(Activity activity) {
this.activity = activity;
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.setCanceledOnTouchOutside(true);
imageView = (ImageView) dialog.findViewById(R.id.logoApp);
Button galleryBtn = (Button) dialog.findViewById(R.id.galleryBtn);
galleryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
galleryIntent();
}
});
dialog.show();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
activity.startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(activity,"sdddddsss",Toast.LENGTH_LONG).show();
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
onSelectFromGalleryResult(data);
}else{
// ...
}
}
}
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
imageView.setImageBitmap(bm);
}
}
我遵循此http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
答案 0 :(得分:3)
在活动A中显示对话框时,请将对活动A的引用设置为参数:
alert.showDialog(this);
然后在CustomDialog中,将此引用另存为活动变量:
public void showDialog(Activity activity) {
this.activity = activity;
...}
这意味着this.activity
是活动A的实例。稍后在您的galleryIntent()中,您为以下结果启动活动:
private void galleryIntent() {
...
activity.startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
}
这意味着onActivityResult将在活动A中而不是在“自定义”对话框中调用,因为您使用了activity
变量。
您有2个修复选项:
1)将activity.startActivityForResult
替换为CustomDialog.this.startActivityForResult
2)将onActivityResult
代码从CustomDialog移到活动A
答案 1 :(得分:1)
您正在呼叫:startActivityForResult
参考上的activity
与您希望在其中调用CustomDialog
的{{1}}不同。我不记得曾经在不是前台的活动实例上调用onActivityResult
-我不确定它是否会起作用。我建议您更改:从startActivityForResult
更改为activity.startActivityForResult
顺便说一句。在您的startActivityForResult
中,您曾经两次致电onActivityResult
。这是不正确的。
答案 2 :(得分:0)
之所以没有调用onActivityResult()的原因是因为在启动结果活动时即调用了onActivityResult(),即startActivityForResult(...),然后在启动的活动返回或结束时调用了onActivityResult()