Android 如何从另一个片段打开一个新片段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21028786/
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-08-20 03:52:08  来源:igfitidea点击:

How do I open a new fragment from another fragment?

androidandroid-fragmentsonclicklistenerandroid-button

提问by Hultan

I tried making a navigation between fragments. I've got the NewFragment.javawith the new fragment working. My problem is:

我尝试在片段之间进行导航。我已经有了NewFragment.java新的片段工作。我的问题是:

How do I make this onClickListenerrun NewFragment.javacorrectly?

我如何使这个onClickListener运行NewFragment.java正确?

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

        Intent i = new Intent(getActivity(), NewFragment.class);
        startActivity(i);

    }
});

FYI: This is from inside a fragment (I don't know if that matters).

仅供参考:这是来自片段内部(我不知道这是否重要)。

回答by Narendra

Add following code in your click listener function,

在单击侦听器函数中添加以下代码,

NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
             .replace(R.id.Layout_container, nextFrag, "findThisFragment")
             .addToBackStack(null)
             .commit();

The string "findThisFragment"can be used to find the fragment later, if you need.

"findThisFragment"如果需要,该字符串可用于稍后查找片段。

回答by Nipuna Dilhara

This is more described code of @Narendra's code,

这是@Narendra 代码的更多描述代码,

First you need an instance of the 2nd fragment. Then you should have objects of FragmentManager and FragmentTransaction. The complete code is as below,

首先,您需要第二个片段的实例。那么你应该有 FragmentManager 和 FragmentTransaction 的对象。完整的代码如下,

Fragment2 fragment2=new Fragment2();
FragmentManager fragmentManager=getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_main,fragment2,"tag");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Hope this will work. In case you use androidx, you need getSupportFragmentManager() instead of getFragmentManager().

希望这会奏效。如果您使用 android x,则需要 getSupportFragmentManager() 而不是 getFragmentManager()。

回答by vipul mittal

You should create a function inside activity to open new fragment and pass the activity reference to the fragment and on some event inside fragment call this function.

您应该在活动内部创建一个函数来打开新片段并将活动引用传递给片段,并在片段内部的某个事件上调用此函数。

回答by Vinod Joshi

@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
    super.onListItemClick(l, v, pos, id);
    UserResult nextFrag= new UserResult();
    this.getFragmentManager().beginTransaction()
    .replace(R.id.content_frame, nextFrag, null)
    .addToBackStack(null)
    .commit();  
}

回答by Parinda Rajapaksha

Use this,

用这个,

AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();

回答by All ?? Vаи?тy

Using Kotlin to replace a Fragmentwith another to the container, you can do

使用 Kotlin 将 a 替换为Fragment另一个container,您可以这样做

button.setOnClickListener {
    activity!!
        .supportFragmentManager
        .beginTransaction()
        .replace(R.id.container, NewFragment.newInstance())
        .commitNow()
}

回答by Jatin

first of all, give set an ID for your Fragment layout e.g:

首先,为您的 Fragment 布局设置一个 ID,例如:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
**android:id="@+id/cameraFragment"**
tools:context=".CameraFragment">

and use that ID to replace the view with another fragment.java file. e.g

并使用该 ID 将视图替换为另一个 fragment.java 文件。例如

 ivGallary.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          UploadDoc uploadDoc= new UploadDoc();
          (getActivity()).getSupportFragmentManager().beginTransaction()
                  .replace(**R.id.cameraFragment**, uploadDoc, "findThisFragment")
                  .addToBackStack(null)
                  .commit();
      }
  });

回答by Mbanda

 Fragment fr = new Fragment_class();
             FragmentManager fm = getFragmentManager();
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
            fragmentTransaction.add(R.id.viewpagerId, fr);
            fragmentTransaction.commit();

Just to be precise, R.id.viewpagerIdis cretaed in your current class layout, upon calling, the new fragment automatically gets infiltrated.

准确地说,R.id.viewpagerId是在您当前的类布局中创建的,在调用时,新片段会自动被渗透。

回答by Gerry R

Adding to @Narendra solution...

添加到@Narendra 解决方案...

IMPORTANT: When working with fragments, navigations is closely related to host acivity so, you can't justo jump from fragment to fragment without implement that fragment class in host Activity.

重要提示:在使用片段时,导航与宿主活动密切相关,因此,如果没有在宿主 Activity 中实现该片段类,就不能只是从片段跳转到片段。

Sample:

样本:

public class MyHostActivity extends AppCompatActivity implements MyFragmentOne.OnFragmentInteractionListener {

public class MyHostActivity extends AppCompatActivity implements MyFragmentOne.OnFragmentInteractionListener {

Also, check your host activity has the next override function:

另外,检查您的主机活动是否具有下一个覆盖功能:

@Override public void onFragmentInteraction(Uri uri) {} Hope this helps...

@Override public void onFragmentInteraction(Uri uri) {} 希望这可以帮助...

回答by Māris Skrīvelis

Well my problem was that i used the code from the answer, which is checked as a solution here, but after the replacement was executed, the first layer was still visible and functionating under just opened fragment. My solution was simmple, i added

好吧,我的问题是我使用了答案中的代码,此处将其检查为解决方案,但是在执行替换后,第一层仍然可见并且在刚刚打开的片段下运行。我的解决方案很简单,我补充说

.remove(CourseListFragment.this)

the CourseListFragment is a class file for the fragment i tried to close. (MainActivity.java, but for specific section (navigation drawer fragment), if it makes more sense to you) so my code looks like this now :

CourseListFragment 是我试图关闭的片段的类文件。(MainActivity.java,但对于特定部分(导航抽屉片段),如果它对您更有意义)所以我的代码现在看起来像这样:

LecturesFragment nextFrag= new LecturesFragment();

                    getActivity().getSupportFragmentManager().beginTransaction()
                            .remove(CourseListFragment.this)
                            .replace(((ViewGroup)getView().getParent()).getId(), nextFrag, "findThisFragment")
                            .addToBackStack(null)
                            .commit();

And it works like a charm for me.

它对我来说就像一种魅力。