RadioGroup+OnCheckedChangeListener实现安卓按钮切换

这里写图片描述
点击一下
这里写图片描述
再点击一下
这里写图片描述

如图所示,如何实现有几个按钮的情况下进行点击切换呢?

分两步,一是xml界面的搭建,一是javaw文件的逻辑支持

如果遇到一组相似的按钮,我们需要用到RadioGroup组,而且他是继承自LinearLayout,
可以设置vertical和horizontal两种结构,默认的是vertical结构

<RadioGroup
 android:id="@+id/comment"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RadioButton
        android:id="@+id/assumption"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="如果今天是周五"/>
    <RadioButton
        android:id="@+id/condition"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="那么昨天就是明天"/>
</RadioGroup>

<--!输出文本,按下按钮后将出现按钮上的文本-->
<TextView
    android:id="@+id/question"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="请问今天是周几"
    app:layout_constraintBottom_toBottomOf="parent"
    android:textSize="30sp"
    />


java文件中

package com.example.a18307.link;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//取xml文件中的按钮组和文本
        RadioGroup comment=(RadioGroup)findViewById(R.id.comment);
        final TextView question=(TextView)findViewById(R.id.question);

//为按钮组设置OnCheckedChangeListener监听器,检测按钮变化,设置的监听器同时实例化,可以不用传参。另一种方法是新写一个监听器类,然后添加。
        comment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
radioGroup是接受监测的按钮组,i是每个按钮自带的ID,按在xml中命名的顺序排布
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
//获取因点击而变化的id
                int radioId=radioGroup.getCheckedRadioButtonId();
//把id指示的按钮返回给当前显示的按钮,看起来就像是因为点击而切换按钮
                RadioButton radioButton=(RadioButton)MainActivity.this.findViewById(radioId);
//把当前显示的按钮的值放到显示文本Textview中
                question.setText(radioButton.getText());
            }
        });
    }

}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值