TAGS :Viewed: 11 - Published at: a few seconds ago

[ Android - How to properly show a fragment when a radio button is checked by default? ]

I'm trying to make an app using fragments, based on this docs: Fragments.

As far as I can understand, I need:

  • Host Activity [DONE]:

This is my host activity (.java)

    public class SphereSurfaceArea extends AppCompatActivity
    {
       RadioGroup rg_sa;
       RadioButton rb_grad, rb_gvol, rb_gcirc;

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

        rg_sa = (RadioGroup) findViewById(R.id.rg_sphere_sa);

        rb_grad = (RadioButton) findViewById(R.id.rb_given_rad);
        rb_gvol = (RadioButton) findViewById(R.id.rb_given_vol);
        rb_gcirc = (RadioButton) findViewById(R.id.rb_given_circ);

        rb_grad.setChecked(true); //Here the radio button is checked 

        rg_sa.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                switch (checkedId)
                {
                    case R.id.rb_given_rad:
                        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();

                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                        fragmentTransaction.add(R.id.fragment_container, new GivenRad());

                        fragmentTransaction.commit();

                        break;
                 }
              }
           });
        }
     }

This is my host XML layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_sphere_surface_area"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="dev.indie.nayir55.geometrycompanion.SolidShapesOperations.SphereOperations.SphereSurfaceArea">

    <RadioGroup
        android:id="@+id/rg_sphere_sa"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:gravity="center"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <!--This is the button checked by default-->
        <RadioButton
            android:id="@+id/rb_given_rad"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_horizontal"
            android:layout_weight="1"
            android:gravity="center_horizontal|center|start"
            android:text="Given radious"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:textSize="18sp"
            />

        <RadioButton
            android:id="@+id/rb_given_vol"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center"
            android:layout_weight="1"
            android:gravity="center_horizontal|center|start"
            android:text="Given volume"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:textSize="18sp"/>

        <RadioButton
            android:id="@+id/rb_given_circ"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_horizontal"
            android:layout_weight="1"
            android:gravity="center_horizontal|center|start"
            android:text="Given circumference"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:textSize="18sp"/>
    </RadioGroup>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rg_sphere_sa">

    </FrameLayout>
</android.support.constraint.ConstraintLayout>
  • Fragment(s) [DONE]:

This is my fragment .java code:

public class GivenRad extends Fragment
{
    public GivenRad()
    {
        // Required empty public constructor
    }

    public static GivenRad newInstance()
    {
        return new GivenRad();
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_given_rad, container, false);
        return rootView;
    }

}

This is my fragment XML layout:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             xmlns:tools="http://schemas.android.com/tools"
                                             android:layout_width="match_parent"
                                             android:layout_height="match_parent"
                                             tools:context="dev.indie.nayir55.geometrycompanion.Fragments.SolidGeometry.FragSphere.GivenRad">
    <TextView
        android:text="Radious"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView9"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="16dp"/>
</android.support.constraint.ConstraintLayout>
  • ID to the container [DONE]:

Inside my host XML layout you'll find the container:

<FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rg_sphere_sa">

    </FrameLayout>
  • A way to dynamically use fragments [DONE]:

Here I'm trying to use fragments dynamically using the radio buttons and a switch:

rg_sa.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                switch (checkedId)
                {
                    case R.id.rb_given_rad:
                        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();

                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                        fragmentTransaction.add(R.id.fragment_container, new GivenRad());

                        fragmentTransaction.commit();

                        break;
                }
            }
        });

So... my problem is this:

Using a radio group and radio buttons I set a radio button checked by default, and when I open the host activity containing the radio buttons and the fragment, the radio button is checked but it is not showing the fragment until I check again the button, also if I use if statement is the same result what am I doing wrong?

Answer 1


What is happening is that you are checking the radio by default, and only loading fragments if the radio is changed or pressed. I would suggest loading the default fragment at runtime to avoid having to hit the button to get it to show up.

Answer 2


At the moment, you are only loading a fragment in response to an event in onCheckedChanged(). You also need to load the appropriate fragment in onCreate(). To start, you might want to just copy and paste the code which loads a fragment directly into onCreate(). Eventually you can reduce duplicated code by putting the fragment-loading code in a method (i.e. loadFragment()) which is called from onCreate() and from onCheckedChanged().

Answer 3


I will answer my own question

Here is another approach of the desired behavior I was looking for

Change a fragment

Hope this helps