简体   繁体   English

Android-如何在默认情况下选中单选按钮时正确显示片段?

[英]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 . 我正在尝试根据以下文档使用片段制作应用程序: Fragments

As far as I can understand, I need: 据我了解,我需要:

  • Host Activity [DONE]: 主持人活动[DONE]:

This is my host activity (.java) 这是我的主机活动(.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布局:

<?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: 这是我的片段.java代码:

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: 这是我的片段XML布局:

<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]: 容器的ID [DONE]:

Inside my host XML layout you'll find the container: 在我的宿主XML布局内,您将找到容器:

<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]: 动态使用片段[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? 使用单选组和单选按钮,我将单选按钮设置为默认选中状态,当我打开包含单选按钮和片段的主机活动时,将选中单选按钮,但是直到再次检查该按钮时,它才会显示片段,另外,如果我使用if语句的结果相同,那我在做什么错呢?

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. 我建议在运行时加载默认片段,以避免不得不点击按钮使其显示出来。

At the moment, you are only loading a fragment in response to an event in onCheckedChanged() . 目前,您仅在响应onCheckedChanged()的事件时加载片段。 You also need to load the appropriate fragment in onCreate() . 您还需要在onCreate()加载适当的片段。 To start, you might want to just copy and paste the code which loads a fragment directly into onCreate() . 首先,您可能只需要复制并将粘贴片段的代码直接粘贴到onCreate() Eventually you can reduce duplicated code by putting the fragment-loading code in a method (ie loadFragment() ) which is called from onCreate() and from onCheckedChanged() . 最终,您可以通过将片段加载代码放入一个方法(即loadFragment() )中来减少重复代码,该方法从onCreate()onCheckedChanged()

I will answer my own question 我会回答我自己的问题

Here is another approach of the desired behavior I was looking for 这是我想要的行为的另一种方法

Change a fragment 更改片段

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM