1、项目需求
- 本项目是一个安卓项目,启动页面有三个单选按钮
- 单选按钮的内容分别显示one,two,three
- 单选按钮的默认选择是one
- 点击任何一个单选按钮,toast提示下一个单选按钮的内容
- 点击最后一个单选按钮,toast提示第一个单选按钮的内容
2、项目分析
- RadioGroup的点击监听
(1)RadioGroup需要设置监听器,监听器的作用是提示toast
(2)判断点击按钮的位置,获取要提示的按钮的位置
3、布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gui.radiobuttontoast.MainActivity">
<RadioGroup
android:id="@+id/number"
android:checkedButton="@+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
<RadioButton
android:id="@+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="two"/>
<RadioButton
android:id="@+id/three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="three"/>
</RadioGroup>
</RelativeLayout>
4、Activity
package com.example.gui.radiobuttontoast;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//声明组件
RadioGroup number;
int count;
RadioButton three;
int index;//要提示的radio的index
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取组件
number = (RadioGroup) findViewById(R.id.number);
count = number.getChildCount();
three=(RadioButton)findViewById(R.id.three);
number.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//如果是最后一个,index就是0;如果不是,索引就加1;
if(checkedId==three.getId()){
index=0;
}else{
index=number.indexOfChild(number.findViewById(checkedId))+1;
}
RadioButton radio=(RadioButton)number.getChildAt(index);
Toast.makeText(getApplicationContext(), radio.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
5、运行结果
apk下载链接:https://pan.baidu.com/s/1rv_lbz5M5rR7uzszkjtuuQ
提取码:3l0w
运行结果:
1、启动页:
2、选中two
3、选中three
4、选中one