简体   繁体   English

用活动组内的另一个片段替换一个片段

[英]Replacing a fragment with another fragment inside activity group

I have a fragment inside a group activity and I want to replace it with another fragment:我在小组活动中有一个片段,我想用另一个片段替换它:

FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

It works fine when it is done as a seperate project without using activity group, every thing works fine in log cat as control goes inside getview(), but no view is visible, not even any exception arises, I want the book detail fragment to be replaced by section detail fragment.当它作为一个单独的项目完成而不使用活动组时它工作正常,当控制进入 getview() 时,log cat 中的每件事都工作正常,但没有视图可见,甚至没有出现任何异常,我希望书籍详细信息片段由部分详细信息片段替换。

Xml of book detail fragment has id book_description_fragment and xml for section description fragment has id section_description_fragment.书籍详细信息片段的 Xml 的 ID 为 book_description_fragment,章节描述片段的 xml 的 ID 为 section_description_fragment。

The above code is in onClick method of an item, I want that when user taps on an item in horizontal scroll view, then the fragment changes.上面的代码在项目的 onClick 方法中,我希望当用户在水平滚动视图中点击项目时,片段会发生变化。

Fragments that are hard coded in XML, cannot be replaced.用 XML 硬编码的片段无法替换。 If you need to replace a fragment with another, you should have added them dynamically, first of all.如果您需要用另一个片段替换一个片段,首先应该动态添加它们。

Note: R.id.fragment_container is a layout or container of your choice in the activity you are bringing the fragment to.注意: R.id.fragment_container是您在将片段带到的活动中选择的布局或容器。

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Please see this Question请看这个问题

You can only replace a " dynamically added fragment ".您只能替换“动态添加的片段”。

So, if you want to add a dynamic fragment, see this example.因此,如果要添加动态片段,请参阅示例。

I've made a gist with THE perfect method to manage fragment replacement and lifecycle .我已经制定了管理片段替换生命周期的完美方法的要点。

It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).它只用一个新的片段替换当前片段,如果它不相同并且它不在 backstack 中(在这种情况下它会弹出它)。

It contain several option as if you want the fragment to be saved in backstack.它包含多个选项,就好像您希望将片段保存在 backstack 中一样。

=> See Gist here =>在这里查看要点

Using this and a single Activity, you may want to add this to your activity:使用此和单个活动,您可能希望将其添加到您的活动中:

@Override
public void onBackPressed() {
    int fragments = getSupportFragmentManager().getBackStackEntryCount();
    if (fragments == 1) {
            finish();
            return;
    }

    super.onBackPressed();
}

Use the below code in android.support.v4在 android.support.v4 中使用以下代码

FragmentTransaction ft1 = getFragmentManager().beginTransaction();
WebViewFragment w1 = new WebViewFragment();
w1.init(linkData.getLink());
ft1.addToBackStack(linkData.getName());
ft1.replace(R.id.listFragment, w1);
ft1.commit();

Use this code using v4使用 v4 使用此代码

 ExampleFragment newFragment = new ExampleFragment();     
 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();  
 // Replace whatever is in the fragment_container view with this fragment,  
 // and add the transaction to the back stack so the user can navigate back   
 transaction.replace(R.id.container, newFragment);
 transaction.addToBackStack(null);  
 // Commit the transaction   
 transaction.commit();

Use ViewPager.使用 ViewPager。 It's work for me.这对我有用。

final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager); 
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        viewPager.setCurrentItem(1);
    }
});

hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about 1- How to switch fragment with other.希望你一切顺利。当我开始使用Android Fragments我也遇到了同样的问题,然后我阅读了 1- 如何与其他片段切换。 2- How to add fragment if Fragment container does not have any fragment. 2- 如果Fragment container没有任何片段,如何添加片段。

then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.然后经过一些研发,我创建了一个功能,该功能在许多项目中对我有帮助,直到现在我仍在使用这个简单的功能。

public void switchFragment(BaseFragment baseFragment) {
    try {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
        if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
            ft.add(R.id.home_frame, baseFragment);
        } else {
            ft.replace(R.id.home_frame, baseFragment);
        }
        ft.addToBackStack(null);
        ft.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

enjoy your code time :)享受你的代码时间:)

You Can Use This code您可以使用此代码

((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();

or You Can This Use Code或者你可以使用代码

YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);

        if (fragments==null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
        }

I change fragment dynamically in single line code我在单行代码中动态更改片段
It is work in any SDK version and androidx它适用于任何 SDK 版本和 androidx
I use navigation as BottomNavigationView我使用导航作为BottomNavigationView

    BottomNavigationView btn_nav;
    FragmentFirst fragmentFirst;
    FragmentSecond fragmentSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        fragmentFirst = new FragmentFirst();
        fragmentSecond = new FragmentSecond ();
        changeFragment(fragmentFirst); // at first time load the fragmentFirst
        btn_nav = findViewById(R.id.bottomNav);
        btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch(menuItem.getItemId()){
                    case R.id.menu_first_frag:
                        changeFragment(fragmentFirst); // change fragmentFirst
                        break;
                    case R.id.menu_second_frag:
                        changeFragment(fragmentSecond); // change fragmentSecond
                        break;
                        default:
                            Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }
public void changeFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
    }

you can use simple code its work for transaction您可以使用简单的代码进行交易

Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit(); 

In kotlin you can do:在 kotlin 中,您可以执行以下操作:

// instantiate the new fragment
val fragment: Fragment = ExampleFragment()

val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()

This will work if you're trying to change the fragment from another fragment.如果您尝试从另一个片段更改片段,这将起作用。

Objects.requireNonNull(getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment_container,new NewFragment())

NOTE As stated in the above answers, You need to have dynamic fragments.注意如上述答案所述,您需要拥有动态片段。

You can use fragment-ktx您可以使用片段 ktx

// If you are in fragmet
childFragmentManager.beginTransaction()

// or if you are in activiry
supportFragmentManager.beginTransaction()

// Create and commit a new transaction
supportFragmentManager.commit {
  setReorderingAllowed(true)
  // Replace whatever is in the fragment_container view with this fragment
  replace<ExampleFragment>(R.id.fragment_container)
}

To replace a fragment with another one do this, Note that R.id.fragment comes from the id that you give to the first tag of the fragment in the XML.要用另一个片段替换一个片段,请执行此操作,请注意 R.id.fragment 来自您为 XML 中片段的第一个标签提供的 ID。

barAudioPlaying.setOnClickListener(view -> {
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment,new HomeFragment())
                        .commit();

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

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