startActivityForResult在Fragment中不起作用

时间:2014-02-17 10:38:34

标签: android android-fragments

我目前正与Fragment合作。我想从gallery&中选择Image将它显示在片段类上。但是这里的startActivityForResult()在Fragment中不起作用。

我的片段类

Button loadimage=(Button) view.findViewById(R.id.loadButton);
    loadimage.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
@Override
public 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 cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        imgview.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }

    }

2 个答案:

答案 0 :(得分:19)

在Activity类中:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode,resultCode,data);
}

在片段中:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    //  Handle activity result here  
}

启动片段结果的活动:

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1); 

答案 1 :(得分:5)

覆盖父级片段活动中的onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
}