java 如何从另一个 Activity 打开或启动 Fragment?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32553782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:23:23  来源:igfitidea点击:

How to open or launch a Fragment from another Activity?

javaandroidandroid-fragmentsandroid-intentandroid-activity

提问by Sebastian Delgado

from the adapter of a RecyclerView which is contained in an Activity, i'm trying to launch a fragment when an element of the RecyclerView is pressed, this is my code right now :

从包含在 Activity 中的 RecyclerView 的适配器中,我试图在按下 RecyclerView 的元素时启动一个片段,这是我现在的代码:

@Override
public void onClick(View v) {
    Intent intent;

    int position = getAdapterPosition();

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String onoff = preferences.getString("it's", "");

    if (onoff.equalsIgnoreCase("on")) {
        if (position == 0) {

            CategoriesRecyclerView.fragSubreddit = "aww";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 1) {

            CategoriesRecyclerView.fragSubreddit = "food";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 2) {

            CategoriesRecyclerView.fragSubreddit = "funny";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 3) {

            CategoriesRecyclerView.fragSubreddit = "gaming";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

    } else if (onoff.equalsIgnoreCase("off")) {

        if (position == 0) {

            CategoriesRecyclerView.fragSubreddit = "gaming";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 1) {

            CategoriesRecyclerView.fragSubreddit = "funny";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 2) {

            CategoriesRecyclerView.fragSubreddit = "food";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 3) {

            CategoriesRecyclerView.fragSubreddit = "aww";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }
    }
}

I Tested it launching some "testing activities" that i created, so i know that everything but the fragment launching works fine.

我测试了它启动了我创建的一些“测试活动”,所以我知道除了片段启动之外的所有内容都可以正常工作。

The error is here :

错误在这里:

intent = new Intent(context, MainFragment.class);
context.startActivity(intent);

I'm launching the Fragment as it was an Activity, so when i run the app it crashes and tells me to declare the MainFragment as an activity in my manifest.

我正在启动 Fragment,因为它是一个 Activity,所以当我运行该应用程序时,它会崩溃并告诉我将 MainFragment 声明为我的清单中的一个 Activity。

How can i launch that Fragment from my Activity?

如何从我的 Activity 启动该 Fragment?

Thanks very much.

非常感谢。

采纳答案by Skizo-oz??S

You cannot start a Fragmentwith Intentsso the method that I recommend to you is :

你不能开始FragmentIntents所以我推荐给你的方法是:

Fragment mFragment = null;
mFragment = new MainFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

For more information see Fragments Transactions documents

有关更多信息,请参阅Fragments Transactions 文档

回答by Olkunmustafa

You can not start a Fragmentusing Intents. Intents provide a communication between activities.

你不能开始Fragment使用Intents。意图提供活动之间的通信。

If you want to launch a Fragmentfrom other Fragmentyou have two options.

如果您想Fragment从其他启动一个,Fragment您有两个选择。

1- You can replace or add a new fragment.

1- 您可以替换或添加新片段。

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction
                .replace( R.id.content_frame, fragment )
                .addToBackStack( null )
                .commit();

In this case The activity has two fragments.

在这种情况下,活动有两个片段。

2- You can launch a new Activity that contains a Fragment.

2- 您可以启动一个包含片段的新活动。

回答by DragonFire

If you are using a Sections Pager Adapter, the simple thing to do would be using an onclick on image view or button like below:

如果您使用的是 Sections Pager Adapter,那么简单的事情就是使用 onclick 图像视图或按钮,如下所示:

In your starting activity (from where you want to go) use put extra to send some information to another activity

在您的开始活动中(从您想去的地方)使用 put extra 将一些信息发送到另一个活动

ivPhotoAlbums.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // Send The Message Receiver ID & Name
        Intent intent = new Intent(v.getContext(), PhotosActivity.class);
        intent.putExtra("viewpager_position", 1);
        v.getContext().startActivity(intent);

    }
});

In your activity in which you want to land (at the end of your setupViewPager() function) catch that extra and use it as position

在您想要登陆的活动中(在 setupViewPager() 函数的末尾)捕获额外的内容并将其用作位置

int position = 0;
Bundle extras = getIntent().getExtras();
if (extras != null) {
    position = extras.getInt("viewpager_position");
}
viewPager.setCurrentItem(position);

Given the Assumption that your setupViewPager() function looks like below in your destination activity

假设您的 setupViewPager() 函数在目标活动中如下所示

SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());

adapter.addFragment(new FriendsAlbumsFragment()); //index 0
adapter.addFragment(new MyAlbumsFragment()); //index 1
adapter.addFragment(new AddPhotosFragment()); //index 2

final ViewPager viewPager = findViewById(R.id.l_center_view_pager_view_pager);
viewPager.setAdapter(adapter);

TabLayout tabLayout = findViewById(R.id.l_top_tabs_tabs);

tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_friends_photos);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_my_photos);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_add_photos);

And Your SectionsPagerAdapter class looks like below (separate public class)

您的 SectionsPagerAdapter 类如下所示(单独的公共类)

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragmentList = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {

        super(fm);

    }

    @Override
    public Fragment getItem(int i) {

        return mFragmentList.get(i);
    }

    @Override
    public int getCount() {

        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {

        mFragmentList.add(fragment);
    }
}

And your center view pager layout is

你的中心视图寻呼机布局是

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v4.view.ViewPager
        android:id="@+id/l_center_view_pager_view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="56dp">

    </android.support.v4.view.ViewPager>

</merge>

Included in another file like this (or not included - in my case it was included)

包含在这样的另一个文件中(或不包含 - 在我的情况下已包含)

<include layout="@layout/layout_center_viewpager" />

This will take you right from an activity to a fragment (in another activity) or from a fragment in one activity to a fragment in another activity...

这将带你从一个活动到一个片段(在另一个活动中)或从一个活动中的一个片段到另一个活动中的一个片段......