RadioGroup的使用


前言:

使用RadioGroup就可以在選擇情況多的時候,簡化代碼

RadioGroup

使用互斥選擇時,會使用RadioGroup標簽下面RadioButton,如下面的代碼:(這樣寫下來,男和女的選擇時垂直的,要想水平的話可以在RadioGroup中添加android:orientation="horizontal")

 1 <RadioGroup
 2         android:layout_width="wrap_content"
 3         android:layout_height="wrap_content"
 4         android:layout_marginTop="40dp"
 5         android:id="@+id/radiogroup">
 6         <RadioButton
 7             android:layout_width="wrap_content"
 8             android:layout_height="wrap_content"
 9             android:id="@+id/nan"
10             android:text="男"/>
11         <RadioButton
12             android:layout_width="wrap_content"
13             android:layout_height="wrap_content"
14             android:id="@+id/nv"
15             android:text="女"/>
16     </RadioGroup>

在Java中的代碼是

 1 public class MainActivity extends AppCompatActivity {
 2     private RadioGroup radiogroup;
 3     private RadioButton nan,nv;
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.activity_main);
 8         nan=(RadioButton)findViewById(R.id.nan);
 9         nv=(RadioButton)findViewById(R.id.nv);
10         radiogroup=(RadioGroup)findViewById(R.id.radiogroup);
11         radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
12             @Override
13             public void onCheckedChanged(RadioGroup group, int checkId) {
14                 switch (checkId){
15                     case R.id.nan:
16                         Toast.makeText(MainActivity.this,"你選擇的是:"+nan.getText(),Toast.LENGTH_SHORT).show();
17                         break;
18                     case R.id.nv:
19                         Toast.makeText(MainActivity.this,"你選擇的是:"+nv.getText(),Toast.LENGTH_SHORT).show();
20                         break;
21                     default:
22                         break;
23                 }
24             }
25         });
26     }
27 }

此時的setOnCheckedChangeListener(設置監聽器)    OnCheckedChangeListener(監聽器)     onCheckedChanged(抽象方法)和RadioButton中的名稱一樣,但是上面的哪些是在RadioGroup中的,而且onCheckedChanged(抽象方法)不同,RadioGroup下的是

1 public void onCheckedChanged(RadioGroup group, int checkId) {}

RadioButton下的是

 

1 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){}

方法的名稱相同,但是參數不同


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM