简体   繁体   English

无法在片段类内编写onActivityResult函数

[英]Can't write onActivityResult function inside fragment class

I have been trying to pick an image from galley and set it to an ImageView. 我一直在尝试从厨房挑选一个图像并将其设置为ImageView。 I am successful in going to gallery and picking the image but can't set it to the ImageView. 我成功地浏览了图片并选择了图像,但无法将其设置为ImageView。 Actually, I can't write the OnActivityResult inside the Fragment class i have written. 实际上,我无法在我编写的Fragment类中编写OnActivityResult。 Below is the code of the class. 下面是该类的代码。

public class MainActivity extends FragmentActivity {

// create object of FragmentPagerAdapter
SectionsPagerAdapter mSectionsPagerAdapter;
String imgDecodableString;
ImageView callerPic;// = (ImageView) findViewById(R.id.callerPic);
// viewpager to display pages
ViewPager mViewPager;
final static int cameraData = 0;
private static int RESULT_LOAD_IMG = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.slideview_fragment);

    // Create the adapter that will return a fragment for each of the five
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

/**
 * A FragmentPagerAdapter that returns a fragment corresponding to one of
 * the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        switch (position + 1) {
            case 1:

                Fragment fragment1 = new Fragment1();
                return fragment1;
            case 2:

                Fragment fragment2 = new Fragment2();
                return fragment2;


            default:
                Fragment fragment = new Fragment1();
                return fragment;
        }
    }

    @Override
    public int getCount() {
        // Show 5 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Fake CALL";
            case 1:
                return "Fake SMS";

        }
        return null;
    }
}



public static class Fragment1 extends Fragment {


    public Fragment1() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.activity_main, container, false);
//THIS PART OF THE CODE I AM HAVING TROUBLE WITH
        ImageView callerPic = (ImageView) view.findViewById(R.id.callerPic);
        callerPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // Start the Intent
                startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

            }
        });

        return view;

    }
}

public static class Fragment2 extends Fragment {

    public Fragment2() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_main2, container, false);

        return view;
    }
 }
}

I have to write the onActivityResult method inside the Fragment1 class but I am not able to write inside it. 我必须在Fragment1类中编写onActivityResult方法,但无法在其中编写。

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            // Set the Image in ImageView after decoding the String
            callerPic.setImageBitmap(BitmapFactory
                    .decodeFile(imgDecodableString));

        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

Can anyone help in fixing this? 有人可以帮助解决此问题吗? Thanks. 谢谢。

It's generally a good pattern to keep your views separately in Fragments and Activities and not "cross-use" them. 通常,将视图分开保存在“片段和活动”中而不是“交叉使用”它们是一个很好的模式。

As NilayDani commented above you can do: 正如NilayDani上面评论的那样,您可以执行以下操作:

getActivity().startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

And the .onActivityResult can be used in your Activity. .onActivityResult可以在您的Activity中使用。

However be wary that when you use Fragments views ie the ImageView callerPic to make sure that this view is available and the fragment has been created and is active. 但是请注意,当您使用“片段”视图时,即ImageView callerPic确保该视图可用并且片段已创建并处于活动状态。 This can easily lead to crashes if you don't pay attention over the Activity-Fragment lifecycle. 如果您不注意Activity-Fragment生命周期,则很容易导致崩溃。

As an advice try to keep your callerPic interacting only into Fragment, if possible of course. 作为建议,如果可能的话,尝试使您的callerPic仅与Fragment交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM