java – Fragment is not replacing marked layout


I'm working on a college project and I'm having trouble replacing a given layout with a fragment. What's happening is, the fragment isn't replacing the layout of the activity but rather merging with it.

This is the block of code that calls the fragment:

    botaoDeFalar.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Bundle bundle = new Bundle();
            String textoParaFragment = editTextPrincipal.getText().toString();
            bundle.putString("oqSeraFalado", textoParaFragment);
            TesteFragment testefragment = new TesteFragment();
            getSupportFragmentManager().beginTransaction().replace(, testefragment).commit();
            oqSeraFalado = textoParaFragment;

The variable BotaoDeFalar is an element of the MainActivity layout (button) that, when pressed, executes this entire block.

the ID LayoutMain is the layout that includes all the other elements of the Activity.

< xmlns:android=""

This is the Java of the fragment in question:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_teste, container, false);
    resultadoPalavra = (TextView) view.findViewById(;
    palavraDigitada = this.getArguments().getString("oqSeraFalado");
    return view;


The result of this when I run the application is that, instead of fragment replacing everything we see on the main screen with the XML from fragment , it adds the XML from the fragment with the XML from the main screen, as if it were merged.


In this way, it is not possible to replace the layout of the activity with that of the fragment.

In terms of layout, what the replace() method does is replace the layout of a fragment, previously added to the indicated view group, with this one.
If no fragment has been added to the indicated view group, the method adds this one and includes its layout in the view group.

So that when adding a fragment, its layout is not merged with the other content, it must be added to an empty group view included in the activity's layout, normally a FrameLayout.

So, if you want to replace all the content of the activity layout, this layout should have only one FrameLayout with nothing inside, then use two fragments, the one that already has and another one for the content that had the activity.

Scroll to Top