温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中的一些开关

发布时间:2020-09-02 09:01:37 来源:网络 阅读:394 作者:呆头陈 栏目:移动开发

CheckBox

两种状态:选中(true)和未选中(false)


属性:

android:id="@+id/checkbox"

android:checked="false"   是否选中的状态

android:text="女"


新建:

<CheckBox
    android:id="@+id/cb1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Basketball"
    android:checked="false"
    />

具体实现:

private CheckBox cb;
//初始化CheckBox
cb= (CheckBox) findViewById(R.id.cb1);
//通过设置CheckBox的监听事件来判断checkbox
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(b){
            Toast.makeText(MainActivity.this, "Hi~Basketball", Toast.LENGTH_SHORT).show();
        }
    }
});


可以通过style自定义CheckBox样式


RadioButton和RadioGroup

因为按下后无法自行关闭,所以不建议单独使用


RadioGroup:

RadioButton的集合,提供多选一的使用


属性:

android:orientation="vertical"(垂直排列)或"horizontal"(水平排列)

设置RadioGroup中子类的排列方式


新建View:

<RadioGroup
    android:id="@+id/rg1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioButton
        android:id="@+id/rb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="男" />

    <RadioButton
        android:id="@+id/rb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女" />
</RadioGroup>


具体实现:

private RadioGroup rg;
//初始化RadioGroup
rg= (RadioGroup) findViewById(R.id.rg1);
//实现监听事件
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        //radioGroup 当前组件
        //i RadioGroup中被选中项的ID
        switch(i){
            case R.id.rb1:
                Toast.makeText(MainActivity.this, "You Choose Man", Toast.LENGTH_SHORT).show();
                break;
            case R.id.rb2:
                Toast.makeText(MainActivity.this, "You Choose Woman", Toast.LENGTH_SHORT).show();
                break;
        }

    }
});


RadioGroup中的RadioButton状态改变既可以通过RadioButton来监听也可以通过RadioGroup来监听


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI