Android 如何在单击该片段的按钮时替换片段?

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

How to replace a Fragment on button click of that fragment?

androidandroid-fragmentsandroid-activity

提问by Top Cat

I have an activity containing multiple fragments. Activity initially have fragment and in it have two buttons. Upon clicking this button I have to replace the fragment by new fragment. Each fragment has various widgets and replace the current fragment as various events.

我有一个包含多个片段的活动。活动最初有片段,其中有两个按钮。单击此按钮后,我必须用新片段替换片段。每个片段都有各种小部件,并将当前片段替换为各种事件。

This is my problem. How can I achieve this?

这是我的问题。我怎样才能做到这一点?

Suggest me ideas.

建议我的想法。

回答by Ahmad Raza

you can replace fragment by FragmentTransaction.

您可以用 FragmentTransaction 替换片段。

Here you go.

干得好。

Make an interface.

做一个接口。

public interface FragmentChangeListener 
{
    public void replaceFragment(Fragment fragment); 
}

implements your Fragment holding activity with this interface.

使用此接口实现您的 Fragment 持有活动。

public class HomeScreen extends FragmentActivity implements
        FragmentChangeListener {


         @Override
         public void replaceFragment(Fragment fragment) {
            FragmentManager fragmentManager = getSupportFragmentManager();;     
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(mContainerId, fragment, fragment.toString());
            fragmentTransaction.addToBackStack(fragment.toString());
            fragmentTransaction.commit();   
    }

}

Call this method from Fragments like this.

像这样从 Fragments 调用这个方法。

//In your fragment.

//在你的片段中。

public void showOtherFragment()
{
       Fragment fr=new NewDisplayingFragment();
             FragmentChangeListener fc=(FragmentChangeListener)getActivity();
             fc.replaceFragment(fr);
}

Hope this will work!

希望这会奏效!

NOTE: mContainerId is id of the view who is holding the fragments inside. You should override Fragment's onString() method as well.

注意:mContainerId 是持有片段的视图的 ID。您还应该覆盖 Fragment 的 onString() 方法。

回答by Deep Bhatt

Well even I am learning android...

好吧,即使我正在学习android...

I solved same problem recently, "How to Change Fragment On button's click event".

我最近解决了同样的问题,“如何在按钮的点击事件上更改片段”。

buttonName.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        FragmentTransaction fragmentTransaction = getActivity()
            .getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frame1, new Homefragment());
        fragmentTransaction.commit();
    }
});

Here frame1is id of FrameLayoutwhich have define in my DrawerLayer's XML.

frame1FrameLayout在我的 DrawerLayer 的 XML 中定义的id 。

So now whenever I want fragment transaction I use this code. Each time it will replace frame1instated of your last fragment.

所以现在每当我想要片段交易时,我都会使用此代码。每次它都会替换frame1你最后一个片段的状态。

FragmentTransaction fragmentTransaction = getActivity()
        .getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new newfragment());
fragmentTransaction.commit()

Hope this will help..

希望这会有所帮助..

回答by Dario

You can use the following to replace a fragment on button click of that fragment:

您可以使用以下内容在单击该片段的按钮时替换该片段:

getFragmentManager().beginTransaction().replace(R.id.main_content, new insertFragmentNameHere()).addToBackStack(null).commit();

回答by Erick Moya

From the future 2017 and after, there exists different libraries that triggers Eventsusing Busand now you can use it to tell the activity when an event is trigger in a fragment that it owns.

从未来 2017 年及之后,存在使用总线触发事件的不同库,现在您可以使用它来告诉活动何时在其拥有的片段中触发事件。

Refer to:

参考:

RxBus with RxJava

RxBus 与 RxJava

You can check new architectures suggested by Google

您可以查看 Google 建议的新架构

ViewModel

视图模型

Don't use the approach in the accepted answer, get really ugly with more than 3 different events from fragments

不要在已接受的答案中使用该方法,使用片段中超过 3 个不同的事件变得非常丑陋

回答by Mario Stoilov

  1. Define an interface and call it IChangeListener (or something like that) and define a method inside which will do the work (ex, changeFragment()) (or call another method which will do the work) for changing the fragment).
  2. Make your activity implement the interface, or make an anonymous class within the activity implement it.
  3. Make a paramerized constructor of your fragment, which accepts a IChangeListener parameter.
  4. When initializing the fragment, pass your IChangeListener implementation (the anonymous class or the activity, implementing it)
  5. Make the onClick listener of the button call the changing method of the IChangeListener.
  1. 定义一个接口并调用它 IChangeListener(或类似的东西),并在其中定义一个方法,该方法将完成工作(例如,changeFragment())(或调用另一个将完成工作的方法)以更改片段)。
  2. 使您的活动实现接口,或使活动中的匿名类实现它。
  3. 为您的片段创建一个参数化的构造函数,它接受一个 IChangeListener 参数。
  4. 初始化片段时,传递您的 IChangeListener 实现(匿名类或活动,实现它)
  5. 使按钮的onClick 侦听器调用IChangeListener 的更改方法。

回答by Ramy Elbouhy

you can try this code it's work fine with me , inflate the layout to view , Define the buton and on click ,

你可以试试这个代码,它对我来说很好用,扩大布局以查看,定义按钮并点击,

Button btn_unstable;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home,container,false);

    btn_unstable = (Button)view.findViewById(R.id.btn_unstable);
    btn_unstable.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_replace, new UnstableFragment()).commit();

        }
    });
    return view;
}