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