Search code examples
androidbuttonandroid-studiofragmentmain-activity

How to make a fragment open by default in Android? How to sign button which is clicked?


I'm making football application and it has 4 buttons on the top side of the screen. Every button will open different fragment. Now when I open the app by default it's showing 4 buttons and empty field under them where will be shown content of fragments. What should I do so that one of fragments will be opened by default(as MainActivity but it should stay fragment)? Further, how can I sign(note, mark) the choosen button so that user will see which button is selected now? Thanks, if something is unclear tell me and I'll explain further


Solution

  • You can either add a Fragment statically using the activity's layout XML:

    <fragment android:name="com.example.myapp.myfragment"
                  android:id="@+id/my_fragment"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" />
    

    Or you could add it dynamically when your activity starts up:

    Fragment myFragment = new MyFragment();       
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_container, myFragment).commit();