Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 動態添加RadioButton並切換Fragment

動態添加RadioButton並切換Fragment

編輯:關於Android編程

公司項目中有這樣一個需求,當從網絡獲取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 hashMap = new HashMap();
    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;
        }
    }

}

 

 

布局文件:

 

<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">

    <framelayout android:id="@+id/fl_info_framlayout" android:layout_width="200dp" android:layout_height="200dp" android:background="#4400ffff">


</framelayout></radiogroup></linearlayout>

這裡順便補充一句,項目中我雖然采用了動態添加RadioButton,但是下面可以按鈕點擊左右切換數據的界面並非是用Fragment,而是使用ViewPager實現的。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved