【问题标题】:OnActivityResult called before OnClickOnActivityResult 在 OnClick 之前调用
【发布时间】:2016-03-29 06:30:36
【问题描述】:

我正在尝试创建一个打开画廊的意图(效果很好)。

但是,我需要更改图像按钮以显示用户选择的图片的图像。

问题在于,在GalleryIntent()方法之前调用onActivityResult()方法,该方法导致结果代码不为结果。

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);
}
}

我尝试在清单中的 Activity 中执行 android:launchMode="standard" 但没有成功。

【问题讨论】:

  • 我不确定我是否理解。 onActivityResult 只能在意图返回后调用。
  • 也许你应该检查 onActivityResult 内部的 requestCode == PICTURE_SELECTED
  • 是的,但是首先触发的方法是 onActivityResult 然后它执行意图。 in fact when the image button is selected a message shows "Image opened before" and "Result not ok" (I did this for debugging purposes), then the gallery is opened
  • 从您调用 galleryIntent() 的位置。它不在您发布的代码中的任何位置。
  • 它正在从 XML 文件 中调用

标签: android


【解决方案1】:

你不必开始一个新的图片选择任务-

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 2018-11-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多