从片段内部替换片段 [英] Replacing a fragment from inside a fragment

查看:41
本文介绍了从片段内部替换片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在线阅读内容,要调用另一个片段,要占用FrameLayout,您需要创建一个与活动对话的接口,并且当按钮单击活动中定义的接口内的函数时,会将Fragment替换为另一个片段,但是我没有创建接口,而是尝试直接从片段内部进行操作,并且可以正常工作.那么,为什么我不应该这样做呢?

I read online, that to call another fragment, to take up the FrameLayout, you need to create an interface that talks to the activity and when the button clicked the function inside the interface that is defined in the activity replaces the Fragment with another fragment, but instead of creating the interface, i tried doing it directly from inside the fragment and it worked. So any reasons why i should not be doing this ?

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentOne extends Fragment {


    public FragmentOne() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_one, container, false);

        Button btnONe = view.findViewById(R.id.btnOne);
        btnONe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onButtonPressed();
            }
        });

        return view;
    }

    public void onButtonPressed() {

        FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragmentContainer, new FragmentTwo("Femin Dharamshi did it!"));
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

    }

}

推荐答案

片段是Activity的一部分,片段应通过其父活动托管,如google在Android开发者文档中所述.您可以参考以下链接: https://developer.android.com/training/basics/fragments/communication

Fragments are part of the Activity and fragment should be hosted through their parent activities as stated by google in Android developers docs. You can refer this link:- https://developer.android.com/training/basics/fragments/communicating

这篇关于从片段内部替换片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆