getActivity()。startActivityForResult()不在片段中工作

时间:2015-07-30 07:11:36

标签: android android-fragments imageview

  

我在片段中工作,我需要从中选择一个图像   画廊并将其设置为imageView但   getActivity()。startActivityForResult()现在正在运行

     

我已经检查了许多链接但是所有人都说这个叫   父活动中的方法,但我没有任何父活动   片段在另一个片段内。我也检查了这个链接

startActivityForResult is not working in Fragment

这是我的代码: -

  

MainActivity类: -

public class SabaKuchHomeActivity extends FragmentActivity {

private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

// nav drawer title
private CharSequence mDrawerTitle;

// used to store app title
private CharSequence mTitle;

// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;

private ArrayList<NavDrawerItem> navDrawerItems=new ArrayList<NavDrawerItem>();
private NavDrawerListAdapter adapter;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.home_activity);
    mTitle = mDrawerTitle = getTitle();


    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

    // adding nav drawer items to array
            // Home
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
            // Find People
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
            // Photos
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
            // Communities, Will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
            // Pages
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
            // What's hot, We  will add a counter here
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
            navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));

            // Recycle the typed array
            navMenuIcons.recycle();

            mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

            // setting the nav drawer list adapter
            adapter = new NavDrawerListAdapter(getApplicationContext(),
                    navDrawerItems);
            mDrawerList.setAdapter(adapter);

            // enabling action bar app icon and behaving it as toggle button
            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setHomeButtonEnabled(true);
            //getActionBar().setDisplayShowHomeEnabled(false);


            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                    R.drawable.ic_drawer, //nav menu toggle icon
                    R.string.app_name, // nav drawer open - description for accessibility
                    R.string.app_name // nav drawer close - description for accessibility
            ) {
                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                public void onDrawerClosed(View view) {
                    getActionBar().setTitle(mTitle);
                    //getActionBar().show();
                    // calling onPrepareOptionsMenu() to show action bar icons
                    invalidateOptionsMenu();
                }

                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(mDrawerTitle);
                    // calling onPrepareOptionsMenu() to hide action bar icons
                    //getActionBar().hide();
                    invalidateOptionsMenu();
                }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);

            if (savedInstanceState == null) {
                // on first time display view for first nav item
                displayView(0);
            }
        }

        /**
         * Slide menu item click listener
         * */
        private class SlideMenuClickListener implements
                ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                // display view for selected nav drawer item
                displayView(position);
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // toggle nav drawer on selecting action bar app icon/title
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            // Handle action bar actions click
            switch (item.getItemId()) {
            case R.id.action_search:

                Intent TrendIntent = new Intent(SabaKuchHomeActivity.this,TrendsActivity.class);
                startActivity(TrendIntent);

                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

        /* *
         * Called when invalidateOptionsMenu() is triggered
         */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            // if nav drawer is opened, hide the action items
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            menu.findItem(R.id.action_search).setVisible(!drawerOpen);
            return super.onPrepareOptionsMenu(menu);
        }

        /**
         * Diplaying fragment view for selected nav drawer list item
         * */


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
private void displayView(int position) {
    // update the main content by replacing fragments
    android.support.v4.app.Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new OzoneFragment();
        break;
    case 1:
        fragment = new MyZoneFragment();
        break;
    case 2:
        fragment = new BizZoneFragment();
        break;
    case 3:
        fragment = new EventsFragment();
        break;
    case 4:
        fragment = new PrivacySettingFragment();
        break;
    case 5:
        fragment = new ProfileSettingFragment(); ***This is the fragment where I am moving now***
        break;

    case 6:

        AppContoller.getInstance().pref=getSharedPreferences(AppContoller.getInstance().PREF_NAME, 0);
        Editor editer=AppContoller.getInstance().pref.edit();
        editer.putString(AppContoller.getInstance().USER_ID, "0");
        editer.commit();

        finish();

        break ;

    default:
        break;
    }

    if (fragment != null) {
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();

        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);
}

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

}

  

这里是ProfileSettingFragment()片段: -

 @SuppressLint("NewApi")
public class ProfileSettingFragment extends android.support.v4.app.Fragment implements TabListener {

private ViewPager mPager;
private MyPageAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         View rootView = inflater.inflate(R.layout.profile_setting_fragment, container, false);

         mPager=(ViewPager)rootView.findViewById(R.id.pager);

            mPager.setOffscreenPageLimit(5);
            adapter=new MyPageAdapter(getChildFragmentManager());
            mPager.setAdapter(adapter);


            TabPageIndicator indicater=(TabPageIndicator)rootView.findViewById(R.id.indicator1);
            indicater.setViewPager(mPager);

            indicater.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });

            /*mPager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int position) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });*/

            /*actionBar.addTab(actionBar.newTab().setText("Home").setTabListener(this));
            actionBar.addTab(actionBar.newTab().setText("MiZone").setTabListener(this));
            actionBar.addTab(actionBar.newTab().setText("Top Trending").setTabListener(this));
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);*/

            return rootView;
    }

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

    private class MyPageAdapter extends FragmentStatePagerAdapter
       {
            private List<android.support.v4.app.Fragment> fragments;

        public MyPageAdapter(FragmentManager fm) {
            super(fm);
            // TODO Auto-generated constructor stub
            this.fragments=new ArrayList<android.support.v4.app.Fragment>();
            fragments.add(new ProfileGeneralSetting());
            fragments.add(new ProfileOzoneSetting());
            fragments.add(new ProfileMyzoneSetting());
            fragments.add(new ProfileBizzoneSetting());
            fragments.add(new ProfilePasswordSetting());

        }

        @Override
        public android.support.v4.app.Fragment getItem(int arg0) {
            // TODO Auto-generated method stub
            return fragments.get(arg0);
        }

        @Override
        public CharSequence getPageTitle(int position) {
        // TODO Auto-generated method stub
             switch (position) {
                case 0:
                    return "General";
                case 1:
                    return "Ozone";
                case 2:
                    return "MyZone";
                case 3:
                    return "Biz Zone";
                case 4 :
                    return "Password Setting";
            }
             return null;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return fragments.size();
        }

       }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        mPager.setCurrentItem(tab.getPosition());

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

}
  

这里是嵌套片段,我必须更改图像: -

public class ProfileOzoneSetting extends Fragment implements MiFeelingBase, OnClickListener{

 NetworkImageView genSetOzoneUserImage;

 private ArrayList<String>arrCategoryId=new ArrayList<String>();
 List<String> interestList = new ArrayList<String>();
 String[] interest;
 Boolean setImg ;


 private static final int SELECT_PICTURE = 1;
 private String selectedImagePath;


 Button SettingOzSave;
 private MultipartEntity reqEntity;

 String[] y ={""};


 private String strUserID;
 ImageLoader imageLoader = AppContoller.getInstance().getImageLoader();

 OzoneSettingData ozSettingList = new OzoneSettingData();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.profiesettingozone, container, false);


    genSetOzoneUserImage = (NetworkImageView)rootView.findViewById(R.id.genSetOzoneUserImage);

    SettingOzSave = (Button)rootView.findViewById(R.id.SettingOzSave);

    SettingOzSave.setOnClickListener(this);

    genSetOzoneUserImage.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Log.d("first time", "before method");

            Intent intent  = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
        //startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);

            Log.d("first time", "before method11");
            //startActivityForResult(intent, SELECT_PICTURE);
            getParentFragment().startActivityForResult(intent, SELECT_PICTURE);
            //startActivityForResult(intent, SELECT_PICTURE);
            //((SabaKuchHomeActivity)getActivity()).startActivitForResult(intent, SELECT_PICTURE);
            //getContext().getApplicationContext.startActivityforResult(intent, SELECT_PICTURE);
            //fragment.getApplicationContext.startActivityforResult(intent, SELECT_PICTURE);
            //getActivity().startActivityForResult(intent, SELECT_PICTURE);
            //startActivityForResult(intent, SELECT_PICTURE);
            //((SabaKuchHomeActivity)getActivity()).startActivitForResult(intent, SELECT_PICTURE);

            Log.d("first time", "before method22");

        }
    });


    APIAccess.fetchData(ProfileOzoneSetting.this, getActivity(), getActivity());
    return rootView;
}
@Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {


    Log.d("first time", "before method33");
      super.onActivityResult(requestCode, resultCode, data);

        Log.d("first time", "before method44");

        if (requestCode == SELECT_PICTURE && resultCode ==Activity.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();
            genSetOzoneUserImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            setImg = true;
         }
          }

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
     AppContoller.getInstance().pref=getActivity().getSharedPreferences(AppContoller.getInstance().PREF_NAME, 0);



@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

请让我知道我在这里犯了什么错误???

更新

我确实更新了SabaKuchHomeActivityProfileSettingFragment

13 个答案:

答案 0 :(得分:9)

问题是你在Fragment中实现 onActivityResult 并调用 getActivity()。startActivityForResult(...)。因为您要从Activity启动Activity,所以 onActivityResult(...)方法调用将转到启动新Activity的Activity。

所以您需要做的就是删除 getActivity()部分,并在您的片段中调用onActivityResult(...)!

编辑: 正如您在GrepCode中看到的那样,Fragment startActivityForResult 中的代码与Activity startActivityForResult 不同。这肯定是巧合......

答案 1 :(得分:6)

你不应该使用

getActivity().startActivityForResult(...)

只需使用

startActivityForResult(...)

这样就可以调用片段中的onActivityResult

答案 2 :(得分:1)

尝试一下, 当您调用startActivityForResult()时,首先调用Activity的onActivityResult(),然后调用其片段的onActivityResult(),但不会对嵌套片段进行此调用。因此,在你的片段的onActivityResult()中,你必须以某种方式获取当前加载的片段,如果需要则对其进行类型转换,然后调用一个写在其中的方法,你传递给OnActivityResult()。

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

  // notifying nested fragments (support library bug fix)
  final FragmentManager childFragmentManager = getChildFragmentManager();

  if (childFragmentManager != null) {
    final List < Fragment > nestedFragments = childFragmentManager.getFragments();

    if (nestedFragments == null || nestedFragments.size() == 0) return;

    for (Fragment childFragment: nestedFragments) {
      if (childFragment != null && !childFragment.isDetached() && !childFragment.isRemoving()) {
        childFragment.onActivityResult(requestCode, resultCode, data);
      }
    }
  }
}

片段中的代码onActivityResult()看起来像, 尝试从fragmentManager或viewPagerAdapter的帮助中获取片段 还尝试将startActivityForResult称为

fragment.getParentFragment().startActivityForResult();

而不是

fragment.startActivityForResult();

将它放在外部片段中以访问当前加载的片段

MyFragment myFragment = (MyFragment)pagerAdapter.getCurrentFragment();
myFragment.myMethod();

以下代码中的代码将返回当前加载的片段,请记住以下内容仅供您理解,相应地在代码中使用

Fragment fragment;

@Override
public Fragment getItem(int index) {
    fragment = new FragFilter();
    return fragment;
}

public Fragment getCurrentFragment() {
    return this.fragment;
}

答案 3 :(得分:1)

删除

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

在您的活动和第一个片段中并在嵌套片段中维护它

并且即使没有工作也会在将片段初始化为

时传递您的活动实例
fragment = new ProfileSettingFragment(activity);

并在片段中创建一个与活动实例一起使用的构造函数 那么你可以在主要活动中调用onActivityResult,并且可以在初始化片段时传递活动参考来获取该活动的数据。

您可以创建一个界面,其中有一个方法将返回一个字符串,通过在您的活动中实现该字符串,您可以通过您的活动参考可用的位置接收数据。

答案 4 :(得分:0)

出于某些原因从

启动ActivityForResult
android.support.v4.app.Fragment

不会工作,它将转到您的活动onActivityResult。如果你使用

android.app.Fragment

它将起作用并返回到Fragment中的onActivityResult。

答案 5 :(得分:0)

虽然我没有测试你的代码。 我代表我写这个答案。

getActivity.startActivityForResult(...)

应该调用Activity onActivityResult。

getParentFragment().onActivityResult(...)

应调用父片段中的onActivityResult。

并且

this.onActivityResult(...)

应该调用当前片段onActivityResult()方法。

您可以尝试这里提到的这些关键字。如果您仍然遇到问题,请告诉我我在GIT上的代码示例

答案 6 :(得分:0)

试试这个:

getContext().getApplicationContext.startActivityforResult();

答案 7 :(得分:0)

onActivityResult使用

中覆盖SabaKuchHomeActivity
public void dispatchTakePictureIntent() {
        final int TAKE_PHOTO_RESULT_CODE = 2345;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent
                .resolveActivity(getActivity().getPackageManager()) != null)
            if (getParentFragment() != null)
                getParentFragment().startActivityForResult(takePictureIntent, TAKE_PHOTO_RESULT_CODE);
            else
                startActivityForResult(takePictureIntent, TAKE_PHOTO_RESULT_CODE);
    }

    public void dispatchChoosePictureIntent() {
        final int CHOOSE_PHOTO_RESULT_CODE = 1234;
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        if (getParentFragment() != null)
            getParentFragment().startActivityForResult(Intent.createChooser(intent, "Choose Picture"),
                    CHOOSE_PHOTO_RESULT_CODE);
        else
            startActivityForResult(Intent.createChooser(intent, "Choose Picture"),
                    CHOOSE_PHOTO_RESULT_CODE);
    }

如果您使用自定义片段或/和viewpager,请使用getParentFragment(),否则使用igonre / remove getParentFragment()

答案 8 :(得分:0)

简单的解决方案只需调用startActivityForResult(/* … */),然后调用片段中的onActivityResult(/* … */)。我经常使用它。

答案 9 :(得分:0)

我们也可以在你的片段中实现onActivityResult()

亲爱的代码,只需从getActivity.移除getActivity.startActivityForResult(...),然后它就会调用您片段的onActivityResult()。  有关详细信息,请参阅此link。 享受你的代码:)

答案 10 :(得分:0)

它变成了一个更长的代码,我将做一个简短的演练 - (因为它是一个赏金),这就是全部。这是我使用的xml。其余的java

<强> activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/rumorsapp.ghaweek"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rumorsapp.ghaweek.MainActivity" >

<android.support.design.widget.TabLayout
    android:id="@+id/tablayou"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="#ff9900"
    android:minHeight="50dp"
    app:tabIndicatorColor="#f09"
    app:tabMode="scrollable"
    app:tabPadding="10dp"
    app:tabSelectedTextColor="#004"
    app:tabTextColor="#fff" >
</android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_marginTop="2dp"
    android:layout_below="@+id/tablayou"
    android:layout_height="match_parent"/>
</RelativeLayout>

我所做的就是创建一个名为 interface ActivityResHan,其中只有一个名为initiate(String fragmentTag);的方法(我的名字很差-i know )逻辑是让我的直接Fragment - (包含viewpager的片段或者有孩子的孩子)实现这个ActivityResHan { {1}}

interface

将调用class ViewPagerFragment extends Fragment implements ActivityResHan{ 从内容提供商处检索联系人。

startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);

@Override public void initiate(String fragmentTag) { calleer = fragmentTag; //this calleer saves the tag Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")); pickContactIntent.setType(Phone.CONTENT_TYPE); startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } direct-Fragment检查onActivityResult是否为空 - (我希望您已经遇到过calleer )如果不是,那么它会调用{ {1}}为他/她的孩子,并通过calleeronActivityResult Tag来识别其子女

现在FragmentManager.findFragmentByTag();的每个孩子,当需要为结果启动活动时,只需找到calleer direct-Fragment - ( viewpageframent )和然后将direct-Fragment投射到Tag并调用Fragment

ActivityResHan

其余代码使这一切都发生

initiate(fragmentTag);

希望它有所帮助。

答案 11 :(得分:0)

In Kotlin

In Activity :-

private var fragment: Fragment? = null

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.fragment_activity)

    fragment = Fragment()

 }

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    fragment?.onActivityResult(requestCode, resultCode, data)
}

In Fragment :- 

button.setOnClickListener {

activity?.startActivityForResult(Intent(parentActivity,
                SecondActivity::class.java), REQUEST_CODE)

}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    val string = data?.getStringExtra("SELECTED_NAME")
    Log.e("Name", "$string")
}

In SecondActivity :- 

override fun onOptionsItemSelected(item: MenuItem): Boolean {

    when (item.itemId) {
        android.R.id.home -> finish()

        R.id.action_filter_apply -> {
            val intent = Intent()
            intent.putExtra("SELECTED_NAME", "Android")
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }

    return super.onOptionsItemSelected(item)
}
 

答案 12 :(得分:-1)

在你的片段中覆盖此方法

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

并将activity变量存储为您的类的成员。 这样,您将始终获得系统提供的正确活动。