简单拓展RadioButton控件使用
如果不看这些,就直接下托
RadioButton和CheckBox的区别:
1、单个RadioButton在选中后,通过点击无法变为未选中
单个CheckBox在选中后,通过点击可以变为未选中
2、一组RadioButton,只能同时选中一个
一组CheckBox,能同时选中多个
3、RadioButton在大部分UI框架中默认都以圆形表示
CheckBox在大部分UI框架中默认都以矩形表示
RadioButton和RadioGroup的关系:
1、RadioButton表示单个圆形单选框,而RadioGroup是可以容纳多个RadioButton的容器
2、每个RadioGroup中的RadioButton同时只能有一个被选中
3、不同的RadioGroup中的RadioButton互不相干,即如果组A中有一个选中了,组B中依然可以有一个被选中
4、大部分场合下,一个RadioGroup中至少有2个RadioButton
5、大部分场合下,一个RadioGroup中的RadioButton默认会有一个被选中,并建议您将它放在RadioGroup中的起始位置
简单代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请选择您的性别:"
android:textSize="9pt"
/>
<RadioGroup android:id="@+id/radioGroup"
android:contentDescription="性别"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioMale"
android:text="男"
android:checked="true"></RadioButton>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioFemale"
android:text="女"></RadioButton>
</RadioGroup>
<TextView
android:id="@+id/tvSex"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您的性别是:男"
android:textSize="9pt"
/>
</LinearLayout>
选中项变更的事件监听:
当RadioGroup中的选中项变更后,您可能需要做一些相应,比如上述例子中,性别选择“女”后下面的本文也相应改变,又或者选择不同的性别后,出现符合该性别的头像列表进行更新,女生不会喜欢使用大胡子作为自己的头像。
TextView tv = null;//根据不同选项所要变更的文本控件
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//根据ID找到该文本控件
tv = (TextView)this.findViewById(R.id.tvSex);
//根据ID找到RadioGroup实例
RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
//绑定一个匿名监听器
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
//获取变更后的选中项的ID
int radioButtonId = arg0.getCheckedRadioButtonId();
//根据ID获取RadioButton的实例
RadioButton rb = (RadioButton)MyActiviy.this.findViewById(radioButtonId);
//更新文本内容,以符合选中项
tv.setText("您的性别是:" + rb.getText());
}
});
}
进入主题
项目中有许多地方用到了RadioGroup和Fragment组合实现切换类似于微博、微信底部的切换
案例1彷微信底部栏
ViewPager+RadioGroup+Fragment 超高仿微信主界面,可通过左右滑动或点击底部RadioButton切换
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="match_parent"
android:layout_height="55dp"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:background="@color/white">
<RadioButton
android:id="@+id/rb_chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/rb_chat_selector"
android:checked="true"
android:text="@string/radiobutton_wechat"
style="@style/style_RadioButton"/>
<RadioButton
android:id="@+id/rb_contacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/rb_contacts_selector"
android:text="@string/radiobutton_contacts"
style="@style/style_RadioButton"/>
<RadioButton
android:id="@+id/rb_discovery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/rb_discovery_selector"
android:text="@string/radiobutton_discovery"
style="@style/style_RadioButton"/>
<RadioButton
android:id="@+id/rb_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/rb_me_selector"
android:text="@string/radiobutton_me"
style="@style/style_RadioButton"/>
</RadioGroup>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/radiogroup"
/>
</RelativeLayout>
style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name="style_RadioButton">
<item name="android:button">@null</item>
<item name="android:layout_weight">0.25</item>
<item name="android:gravity">center</item>
<item name="android:textColor">@color/rb_foucs_color</item>
<item name="android:textSize">12sp</item>
<item name="android:paddingTop">5dp</item>
</style>
</resources>
MainActivity.Java
package com.example.administrator.first.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.example.administrator.first.R;
import com.example.administrator.first.adapter.myFragmentPagerAdapter;
import com.example.administrator.first.fragment.ContactsFragment;
import com.example.administrator.first.fragment.DiscoveryFragment;
import com.example.administrator.first.fragment.MeFragment;
import com.example.administrator.first.fragment.WeChatFragment;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity{
private ViewPager mPager;
private RadioGroup mGroup;
private RadioButton rbChat,rbContacts,rbDiscovery,rbMe;
private ArrayList<Fragment> fragmentList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化界面组件
initView();
//初始化ViewPager
initViewPager();
}
private void initView(){
mPager=(ViewPager)findViewById(R.id.viewPager);
mGroup=(RadioGroup)findViewById(R.id.radiogroup);
rbChat=(RadioButton)findViewById(R.id.rb_chat);
rbContacts=(RadioButton)findViewById(R.id.rb_contacts);
rbDiscovery=(RadioButton)findViewById(R.id.rb_discovery);
rbMe=(RadioButton)findViewById(R.id.rb_me);
//RadioGroup选中状态改变监听
mGroup.setOnCheckedChangeListener(new myCheckChangeListener());
}
private void initViewPager(){
WeChatFragment weChatFragment=new WeChatFragment();
ContactsFragment contactsFragment=new ContactsFragment();
DiscoveryFragment discoveryFragment=new DiscoveryFragment();
MeFragment meFragment=new MeFragment();
fragmentList=new ArrayList<Fragment>();
fragmentList.add(weChatFragment);
fragmentList.add(contactsFragment);
fragmentList.add(discoveryFragment);
fragmentList.add(meFragment);
//ViewPager设置适配器
mPager.setAdapter(new myFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));
//ViewPager显示第一个Fragment
mPager.setCurrentItem(0);
//ViewPager页面切换监听
mPager.setOnPageChangeListener(new myOnPageChangeListener());
}
/**
*RadioButton切换Fragment
*/
private class myCheckChangeListener implements RadioGroup.OnCheckedChangeListener{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.rb_chat:
//ViewPager显示第一个Fragment且关闭页面切换动画效果
mPager.setCurrentItem(0,false);
break;
case R.id.rb_contacts:
mPager.setCurrentItem(1,false);
break;
case R.id.rb_discovery:
mPager.setCurrentItem(2,false);
break;
case R.id.rb_me:
mPager.setCurrentItem(3,false);
break;
}
}
}
/**
*ViewPager切换Fragment,RadioGroup做相应变化
*/
private class myOnPageChangeListener implements ViewPager.OnPageChangeListener{
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position){
case 0:
mGroup.check(R.id.rb_chat);
break;
case 1:
mGroup.check(R.id.rb_contacts);
break;
case 2:
mGroup.check(R.id.rb_discovery);
break;
case 3:
mGroup.check(R.id.rb_me);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
}
myFragmentPagerAdapter
package com.example.administrator.first.adapter;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by Administrator on 2015/6/24.
*/
public class myFragmentPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> list;
public myFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list){
super(fm);
this.list=list;
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
}
拓展:
在MainActivity中实例化各个Fragment和RadioButton和RadioParent的控件,设置好监听器。在这里我定义了一个switchFragment()的方法,判断切换的Fragment是否已经添加过,避免每一次切换Fragment的时候都调用add()或者replace(),而是通过hide()和show(),减少频繁地创建新的实例。
private void switchFragment(Fragment fragment) {
//判断当前显示的Fragment是不是切换的Fragment
if(mFragment != fragment) {
//判断切换的Fragment是否已经添加过
if (!fragment.isAdded()) {
//如果没有,则先把当前的Fragment隐藏,把切换的Fragment添加上
getSupportFragmentManager().beginTransaction().hide(mFragment)
.add(R.id.main_fragment,fragment).commit();
} else {
//如果已经添加过,则先把当前的Fragment隐藏,把切换的Fragment显示出来
getSupportFragmentManager().beginTransaction().hide(mFragment).show(fragment).commit();
}
mFragment = fragment;
}
}
案例2底部栏
实现思路
从图我们基本猜到基本思路如下:
底部选项卡可以使用3个RadioButton组成,并绑定相关的监听器以监听tab切换。
选项卡的上面的部分为一个容器(FrameLayout)以存取3个fragment,可以在tab绑定的监听器中去控制fragment的显示。
布局文件
R.layout.activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RadioGroup
android:id="@+id/ll_rbtn_contain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/rb_first"
style="@style/tab_style"
android:drawableTop="@drawable/tab_first_background"
android:text="first"
android:textColor="@color/radio_colors" />
<RadioButton
android:id="@+id/rb_second"
style="@style/tab_style"
android:drawableTop="@drawable/tab_second_background"
android:text="second"
android:textColor="@color/radio_colors" />
<RadioButton
android:id="@+id/rb_thrid"
style="@style/tab_style"
android:drawableTop="@drawable/tab_third_background"
android:text="thrid"
android:textColor="@color/radio_colors" />
</RadioGroup>
<FrameLayout
android:id="@+id/fl_contain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/ll_rbtn_contain"
android:layout_alignParentTop="true" >
</FrameLayout>
</RelativeLayout>
根视图为相对布局以控制RadioGroup在底部,FrameLayout在RadioGroup的上面
设置选项卡Style
每个RadioButton都设置了统一的tab_style
<!-- 底部Tab按钮样式 -->
<style name="tab_style">
<item name="android:textSize">12sp</item>
<item name="android:gravity">center</item>
<item name="android:background">@drawable/home_btn_bg</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:button">@null</item>
<item name="android:paddingTop">2dp</item>
<item name="android:singleLine">true</item>
<item name="android:layout_weight">1.0</item>
</style>
设置选项卡icon的背景
每个radioButton都设置了Android:drawableTop属性,只要创建三个drawable文件即可 eg :tab_first_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/first_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/first_pressed" android:state_checked="true"/>
<item android:drawable="@drawable/first_normal"/>
</selector>
设置选项卡title的背景
除了选显卡对应的icon要改变外,其对应的title的字体颜色也要随之改变。注意要在res下创建color文件夹并将颜色状态配置文件放在此文件夹下。eg:radio_colors.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/orange_color"/>
<item android:state_checked="true" android:color="@color/orange_color"/>
<item android:color="#aaaaaa" />
</selector>
Main.java
package com.example.tabapp;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.RadioButton;
public class MainActivity extends FragmentActivity implements OnCheckedChangeListener{
//三个选项卡
private RadioButton mRBtnFrist;
private RadioButton mRBtnSecond;
private RadioButton mRBtnThrid;
//存放fragment对应的容器
private FrameLayout mFragmentContain;
private TabFragment mFirstFragment;
private TabFragment mSecondFragment;
private TabFragment mThirdFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentContain = (FrameLayout)findViewById(R.id.fl_contain);
mRBtnFrist = (RadioButton)findViewById(R.id.rb_first);
mRBtnSecond = (RadioButton)findViewById(R.id.rb_second);
mRBtnThrid = (RadioButton)findViewById(R.id.rb_thrid);
mRBtnThrid.setOnCheckedChangeListener(this);
mRBtnThrid.performClick();//此处设置默认第三个选项卡对应的fragment显示
mRBtnFrist.setOnCheckedChangeListener(this);
mRBtnSecond.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//用户当前浏览的选项卡
int checkedWidgetId = buttonView.getId();
mRBtnFrist.setChecked(checkedWidgetId == R.id.rb_first);
mRBtnSecond.setChecked(checkedWidgetId == R.id.rb_second);
mRBtnThrid.setChecked(checkedWidgetId == R.id.rb_thrid);
showFragment(checkedWidgetId);
}else {
//此处记录了用户上次浏览的选项卡
String unCheckFragmentTag = getTagById(buttonView.getId());
TabFragment unCheckFragment = (TabFragment)getSupportFragmentManager().findFragmentByTag(unCheckFragmentTag);
if(unCheckFragment != null){
//隐藏上次显示到fragment,确保fragment不会重叠
getSupportFragmentManager()
.beginTransaction()
.hide(unCheckFragment)
.commit();
}
}
}
/**
* 显示对应的fragment
* @param checkedRadioBtnId
*/
private void showFragment(int checkedRadioBtnId){
String tag = getTagById(checkedRadioBtnId);
TabFragment mainFragment = (TabFragment) getSupportFragmentManager().findFragmentByTag(tag);
if(mainFragment == null){
//如果没有找到对应的fragment则生成一个新的fragment,并添加到容器中
TabFragment newFragment = new TabFragment(tag);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fl_contain, newFragment, tag)
.commit();
}else {
//如果找到了fragment则显示它
getSupportFragmentManager()
.beginTransaction()
.show(mainFragment)
.commit();
}
}
/**
* 为三个fragment分别取三个不同到tag名
* @param widgetId
* @return
*/
private String getTagById(int widgetId){
if(widgetId == R.id.rb_first){
return "first";
}else if(widgetId == R.id.rb_second){
return "second";
}else {
return "thrid";
}
}
}