Activity layout is still visible after adding fragment to the activity

android multiple fragments in one activity example
android fragment vs activity
android fragment example source code
fragments in android example androidhive
fragment inside fragment android example
android replace fragment
fragment activity
how to create fragment in android

This is a really lame question, but I really cannot figure out why it happens, so please help me out.

I have a simple activity and I add a fragment to it dynamically. The problem is that once the fragment is added to the activity, the activity layout is also visible. Why does this happen?

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnLoad = (Button) findViewById(R.id.btn1);

    View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            HelloFragment hello = new HelloFragment();
            fragmentTransaction.add(R.id.rootView, hello, "HELLO");
            fragmentTransaction.commit();
        }
    };

    btnLoad.setOnClickListener(listener);
} 
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootView"
    android:orientation="vertical">
    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btn1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="OK"/>
</LinearLayout>
</LinearLayout>

HelloFragment.java

public class HelloFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {                       
    /** Inflating the layout for this fragment **/
    View v = inflater.inflate(R.layout.hello_fragment_layout, null);
    return v;
}
}

hello_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"      
  android:orientation="vertical" android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="fragment 1"/>
 </LinearLayout>

Convention is to have a FrameLayout that you use fragmentTransaction.replace()/add() on.

You shouldn't have views like TextView and Button in your MainActivity layout file. Instead, have those in another fragment and just have a FrameLayout in your MainActivity xml. Load the fragment with TextView/Button first, and call replace on button click with your new fragment.

Dynamic Layouts using the Fragment Manager –, The Fragment app uses fragments in a number of different ways we have not seen before. In portrait mode the screen renders a fragment for the titles and when one is title fragment is no longer visible, only the details (i.e., play's text) is in focus. In the fragment app example we add fragments to the activity layout in two  Actually fragment used for make a user interface and contributes it’s own layout of the activity. You have must provide a layout for a fragment, to implement the onCreateView() callback method. Create New Project. Okay fine, now time to make android app in add fragment to activity xml. In same way create new project and give some name for the project & choose the Empty Activity for that. After creating project just move on the activity_main.xml file and add the following code. The code is,

Set a background color to your fragment linearLayout and make it clickable

Fragments, When you add a fragment as a part of your activity layout, it lives in a ViewGroup You can return null if the fragment does not provide a UI. but the activity in which this fragment lives is still visible (the foreground activity is  3. Add Fragment To Activity Dynamically Example. activity_dynamic_fragment.xml. This is the main activity layout xml file. It use PercentFrameLayout. You can read article Android PercentFrameLayout PercentRelativeLayout Example to learn more.

The fragment is just another element on the layout. Adding it to the layout does not automatically remove other views. If you want the fragment to replace the content of rootView you need to remove rootview's children views first. Something like:

((LinearLayout)findViewById(R.id.rootView)).removeAllViews();

So your onClick method should look like this:

    @Override
    public void onClick(View v) {
        ((LinearLayout)findViewById(R.id.rootView)).removeAllViews();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        HelloFragment hello = new HelloFragment();
        fragmentTransaction.add(R.id.rootView, hello, "HELLO");
        fragmentTransaction.commit();
    }

Build a flexible UI, Add a Fragment to an Activity at Runtime; Replace One Fragment with not have the large qualifier, so this layout is used when the device  The two buttons and the fragment are in your second activity so I assume after you click one of those buttons and you see the fragment you can hit the back button to go back to the first activity with the list and from there you can go back to the second activity and see the two buttons again, although it feels a bit round about.

your rootview work as container for both fragment and your views on activity. check it and make separate view for fragment.

Creating and Using Fragments, Hiding and showing relevant fragments using the fragment manager. A fragment, like an activity, has an XML layout file and a Java class that onActivityCreated() is called when host activity has completed its onCreate() method. Use onCreate for any standard setup that does not require the activity to be fully created  Adding a fragment to an activity. Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout: Declare the fragment inside the activity's layout file.

I know it's very late to answer this question but for those who are still looking do the following in your activity layout:

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"

android:orientation="vertical">
<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/btn1"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="OK"/>
 </LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rootView"
android:orientation="vertical">
 </RelativeLayout>

And fragment layout to following:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"      
android:orientation="vertical" android:layout_width="match_parent"
 android:background="@color/white"    <!--Add this-->
  android:layout_height="match_parent">
 <TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/btn1"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="OK"/>
</LinearLayout>

[PDF] The Fragment Class, Fragment is visible in the hosting Activity. Paused Fragment's hosting Activity is still visible. Stopped by-side. Fragments are statically added to UI based on a layout file the QuoteViewerActivity when user clicks on a List Item in the. An important rule when dealing with fragments—especially when adding fragments at runtime—is that your activity layout must include a container View in which you can insert the fragment. The following layout is an alternative to the layout shown in the previous lesson that shows only one fragment at a time.

1.1: Creating a Fragment with a UI · GitBook, In the first task, you add the Fragment statically to the Activity layout so that it is The Android framework often re-instantiates a Fragment object when needed, no longer appears in the design preview—but don't worry, it's still there! Add the  One difference when creating a Fragment is that you must use the onCreateView () callback to define the layout. In fact, this is the only callback you need in order to get a fragment running. For example, here's a simple fragment that specifies its own layout: Kotlin Java. More.

Android Add Fragment To Activity Dynamically Example, transaction.add() : Add a Fragment in current activity. transaction.remove() : Remove a Fragment from current activity transaction.hide() : Hide current Fragment, only make it invisible, not destroy This is android fragment layout xml file. How To Fix File Not Found Error When Launching VMware Fusion  Fragments that are declaratively added to an Activity are static and will remain on the Activity until it is destroyed; it is not possible to dynamically replace or remove such a Fragment during the lifetime of the Activity to which it is attached.

Programmatically Working with Android Fragments, During last week's class, my students learned that Fragments (since Android 3) can An Activity's layout can include Fragments as shown below. have no direct visible representation), attach or detach a Fragment, and more. however its state is still being actively managed by the FragmentManager). Imagine that you have one activity and several fragments inside it, which you dynamically add, remove using FragmentManager. A nother problem is to detect when fragment is visible to user.

Comments
  • Your code seems look perfect to me.
  • I know! But why does it now work ?
  • @user3282666 Did you found an issue ? I have the same problem
  • @Spierki My understanding is that a fragment does not replace the layout of the parent activity. So if you want to work with fragments, it would make sense if you have a bank portion of the activity layout and then add fragments to it.
  • Does not work. If I add the transaction to the backstack, and then press the back what I see is an empty layout. I am not yet able to resolve it.
  • I think you must implement onSaveInstanceState save the activity state, in your case a flag indicating that the fragment is created, then on onCreate test the flag and create the fragment.