您的位置:首页 > 移动开发 > Android开发

Android 开发 单选按钮的实现

2015-07-15 20:53 519 查看
选项是由RadioGroup组中的Radiobutton组件实现的

RadioButton是Button的一个子类,继承了Button的属性

布局xml:

<?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="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:height="50px"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/choose"
android:orientation="horizontal"
>
<RadioButton
android:id="@+id/ch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ch1">
</RadioButton>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ch2"
android:text="ch2"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update"
android:id="@+id/update"/>
</LinearLayout>


MainActivity中有两种按钮值需要获取,可简单理解为,选择不同选择时的值。以及点击确认按钮时提交值(确认按钮只是普通的Button)

package com.p3_3;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final RadioGroup choose = (RadioGroup)findViewById(R.id.choose);
choose.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton bt = (RadioButton) findViewById(i);
Log.i("you choose", (String) bt.getText());
}
});
Button button = (Button)findViewById(R.id.update);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for(int i = 0;i<choose.getChildCount();i++) {
RadioButton r = (RadioButton) choose.getChildAt(i);
if(r.isChecked()){
Log.i("Get",(String) r.getText());
break;
}
}
}
});
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: