动态添加RadioButton并切换Fragment

公司项目中有这样一个需求,当从网络获取json数据并解析后,动态的添加按钮,点击时切换对应按钮下存储的各种数据。

如下图:

这里只是单单为了动态添加RadioButton而已,所以数据直接用Fragment替换,效果如下:

MainActivity:

package com.ut.radiobuttondynamicadd;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.ut.radiobuttondynamicadd.factory.UserFragmentFactory;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    @InjectView(R.id.radiogroup_single)
    RadioGroup mRadioGroup;
    @InjectView(R.id.fl_info_framlayout)
    FrameLayout mFlInfoFramlayout;

    //注意,因为是测试,所以这个数组个数不能超过自定义的UserFragment个数,原因什么的自己应该都明白
    private String[] mStrContents = {"孙悟空","猪八戒","沙和尚","白龙马","唐僧"};
    private RadioButton mFirstButton;//第一个按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        initRadioButton();
    }

    /**
     * 动态添加RadioButton
     */
    private void initRadioButton() {
        for (int i = 0; i < mStrContents.length; i++) {
            RadioButton tempButton = new RadioButton(this);
            tempButton.setBackgroundResource(R.drawable.main_radiobutton_bg_selector);	// 设置RadioButton的背景图片
            tempButton.setButtonDrawable(android.R.color.transparent);            // 设置按钮的样式
            tempButton.setPadding(30, 0, 0, 0);                // 设置文字距离按钮四周的距离
            tempButton.setText(mStrContents[i]);

            if (i == 0) {
                mFirstButton = tempButton;
            }

            mRadioGroup.addView(tempButton, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        }

        mRadioGroup.setOnCheckedChangeListener(this);

        if (mFirstButton != null) {
            mFirstButton.setChecked(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        RadioButton rb = (RadioButton) findViewById(checkedId);

        if (rb.isChecked()) {

            for (int i = 0; i < mStrContents.length; i++) {
                if (rb.getText().equals(mStrContents[i])) {
                    Log.d("onCheckedChanged", "当前选中界面:" + i);
                    changeFragment(UserFragmentFactory.createFragment(i));
                }
            }

        }
    }

    private void changeFragment(Fragment targetFragment) {

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_info_framlayout, targetFragment, "fragment")
                .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                .commit();
    }
}

以上基本上便是核心代码。

下面是关于Fragment:

MyBaseFragment:

package com.ut.radiobuttondynamicadd.fragment;

import android.support.v4.app.Fragment;

/**
 * Description:
 * Author:Giousa
 * Date:2016/4/29
 * Email:[email protected]
 */
public class MyBaseFragment extends Fragment {
}

UserFragment1:

package com.ut.radiobuttondynamicadd.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Description:我的界面
 * Author:Giousa
 * Date:2016/4/28
 * Email:[email protected]
 */
public class UserFragment1 extends MyBaseFragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        TextView textView = new TextView(getContext());
        textView.setText("第一个界面");
        textView.setTextColor(Color.RED);

        return textView;
    }
}

剩下的同上。

存储Fragment的工厂类:

UserFragmentFactory

package com.ut.radiobuttondynamicadd.factory;

import com.ut.radiobuttondynamicadd.fragment.MyBaseFragment;
import com.ut.radiobuttondynamicadd.fragment.UserFragment1;
import com.ut.radiobuttondynamicadd.fragment.UserFragment2;
import com.ut.radiobuttondynamicadd.fragment.UserFragment3;
import com.ut.radiobuttondynamicadd.fragment.UserFragment4;
import com.ut.radiobuttondynamicadd.fragment.UserFragment5;
import com.ut.radiobuttondynamicadd.fragment.UserFragment6;
import com.ut.radiobuttondynamicadd.fragment.UserFragment7;
import com.ut.radiobuttondynamicadd.fragment.UserFragment8;

import java.util.HashMap;

/**
 * Description:
 * Author:Giousa
 * Date:2016/4/29
 * Email:[email protected]
 */
public class UserFragmentFactory {

    private static HashMap<Integer, MyBaseFragment> hashMap = new HashMap<Integer, MyBaseFragment>();
    public static MyBaseFragment createFragment(int arg0) {
        //内存中如果已经有当前根据索引生成的fragment,复用之前的fragment对象,内存中没有索引指向的fragment对象,创建
        MyBaseFragment fragment = hashMap.get(arg0);
        if(fragment!=null){
            return fragment;
        }else{
            switch (arg0) {
                case 0:
                    fragment = new UserFragment1();
                    break;
                case 1:
                    fragment = new UserFragment2();
                    break;
                case 2:
                    fragment = new UserFragment3();
                    break;
                case 3:
                    fragment = new UserFragment4();
                    break;
                case 4:
                    fragment = new UserFragment5();
                    break;
                case 5:
                    fragment = new UserFragment6();
                    break;
                case 6:
                    fragment = new UserFragment7();
                    break;
                case 7:
                    fragment = new UserFragment8();
                    break;
            }
            //集合将创建过的fragment,管理起来
            hashMap.put(arg0, fragment);
            return fragment;
        }
    }

}

布局文件:

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

    <RadioGroup
        android:id="@+id/radiogroup_single"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/iv_single"
        android:orientation="horizontal"/>

    <!--RadioButton实现点击切换Fragment-->
    <FrameLayout
        android:id="@+id/fl_info_framlayout"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#4400ffff"/>

</LinearLayout>

这里顺便补充一句,项目中我虽然采用了动态添加RadioButton,但是下面可以按钮点击左右切换数据的界面并非是用Fragment,而是使用ViewPager实现的。

~Demo下载~

时间: 2025-01-14 16:24:50

动态添加RadioButton并切换Fragment的相关文章

Winform 动态添加RadioButton、CheckBox 且任意分组

</pre><pre name="code" class="csharp">//按列分组(n>i且listSize>n) <span style="white-space:pre"> </span>public void showRadioButton(int listSize, List<String> list) { //控件上边缘与容器上边缘的距离 int top =

RadioGroup动态添加RadioButton,并且获得事件

由于有许多的RadioButton是动态的,不是固定的一些,所以需要在代码中,动态的添加到RadioGroup中,下面是我的实现方法. 1.添加RadioButton到RadioGroup中 [java]  view plain copy RadioGroup group; for(int i=0; i<10; i++) { RadioButton tempButton = new RadioButton(this); tempButton.setBackgroundResource(R.dra

RadioGroup结合RadioButton使用切换Fragment片段

界面布局activity_lan_qiu,代码xml设置如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height=&quo

动态添加Fragment碎片

1.      创建待添加的碎片实例. 2.      获取到FragmentManager,在活动中可以直接调用getFragmentManager()方法得到. 3.      开启一个事务,通过调用beginTransaction()方法开启. 4.      向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例 5.      提交事务,调用commit()方法来完成 package com.jia.fragmenttest; import andr

动态添加试题选项按钮 radioButton

最近在做WebView加载试题的功能,但是选项按钮如果放的WebView中,点击时反应很慢.于是把选项用原生的RadioButton,而试题题目和答案放在WebView中.但是选项的个数不确定,所以需要动态添加按钮,一个RadioGroup里面存放若干Radio(这些都是从数据库获取来的数据),然后每次动态生成Radio 以下是动态添加按钮的代码:—————————————————— private LinearLayout layout; //布局 , 可以在xml布局中获得 private 

动态添加Fragment的报错信息

05-29 21:23:28.406: E/AndroidRuntime(23636): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.***.Main}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent

Fragment解析创建和传参,动态添加fragment

一下是个人的一些总结. 为fragment创建XML <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <

android--解决方案--自定义tabhost(动态添加选项+带自动水平滑动选项卡+手势切换选项卡及内容功能)

本文主要解决自定义tabhost的实现,以及集成通过代码动态添加选项卡功能.选项卡水平自动滑动功能.以及通过手势来切换选项卡功能. 下面跟我一起来完成这个完美的解决方案: 1.定义tabwidget选项卡的布局:tab_button.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/r

Android动态添加Fragment

Android动态添加Fragment 效果图如下: 项目结构图如下: Fragment1: package com.demo.dongtaifragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutI