首先说明动态加载的步骤:
- 布局文件建立Fragment,并且定义RadioButton(用于触发点击事件并加载Fragment,非必须)
- 在java代码中获取到RadioGroup
- 设定RadioGroup点击变换的事件setOnCheckedChangeListener
- 设定如果点击的ID和目标ID相等,则触发加载Fragment事件
- 加载指定Fragment
每个步骤在代码中都有相应注释。
首先布局文件中,顶部一个fragment,底部三个按钮radiobutton,在按下某个按钮的时候动态加载对应的fragment。
布局文件如下:
<FrameLayout android:id="@+id/frame" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> //fragment是一个容器,存放动态加载的内容 </FrameLayout> <RadioGroup//radioGroup是三个按钮 android:id="@+id/RG" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <RadioButton android:id="@+id/main" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="主页" android:button="@null" android:gravity="center" android:drawableTop="@mipmap/ic_launcher"/> <RadioButton android:id="@+id/cart" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="购物车" android:button="@null" android:gravity="center" android:drawableTop="@mipmap/ic_launcher"/> <RadioButton android:id="@+id/my" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="我的" android:button="@null" android:gravity="center" android:drawableTop="@mipmap/ic_launcher"/> </RadioGroup>根据ID按下对应按钮加载对应的布局。
在java文件中,先找到radiogroup:
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.RG);
然后设置监听事件:
//这个函数,当选中的radiobutton变化时会触发:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { if(i == R.id.main){ Main main = new Main(MainActivity.this); Fragment fragment = new Fragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frame,main); fragmentTransaction.commit(); } else if(i == R.id.cart){ cart cart = new cart(); Fragment fragment = new Fragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frame,cart); fragmentTransaction.commit(); } else if(i == R.id.my){ my my = new my(); Fragment fragment = new Fragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frame,my); fragmentTransaction.commit(); } } });用if判断当前选中的“i”是哪个按钮,比如
if(i == R.id.main){
如果当前选中的“i”是main的话,则会加载main对应的fragment:
Fragment fragment = new Fragment();//新建一个fragment FragmentManager fragmentManager = getSupportFragmentManager();//新建管理器 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frame,main);//将main(这是对应的fragment类)加入到布局中的frame里 fragmentTransaction.commit();//提交变更.这里的replace是将原本fragment中的东西移除,再添加新的,如果需要叠加,则用add()方法。