单选框与复选框的用法

效果图

单选框与复选框的用法_第1张图片



单选框的使用

// 单选组
        final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);

        //在改变单选按钮组的值时获取
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton sex = (RadioButton) findViewById(checkedId);
                Toast.makeText(MainActivity.this, sex.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });

        Button commit = (Button)findViewById(R.id.commit);

        //  单机其他按钮时获取
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < radioGroup.getChildCount(); i++) {
                    //根据索引值获取单选按钮
                    RadioButton radioButton = (RadioButton) radioGroup.getChildAt(i);
                    if (radioButton.isChecked()) {
                        Toast.makeText(MainActivity.this, radioButton.getText().toString(), Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            }
        });


复选框的使用


/**
         *  功能:实现选中复选框后,“开始”按钮才可用,否则为不可用状态;
         */

        //复选框;
        CheckBox  checkBox = (CheckBox)findViewById(R.id.checkBox);
        final ImageButton imageButton = (ImageButton)findViewById(R.id.start);

        //  复选框的用法;
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                {
                    // 图片按钮可见
                    imageButton.setVisibility(View.VISIBLE);
                }
                else
                {
                    // 图片按钮不可见
                    imageButton.setVisibility(View.INVISIBLE);
                }
                imageButton.invalidate();
            }
        });

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "进入游戏...", Toast.LENGTH_SHORT).show();
            }
        });

    }


开始按钮“选中”与“不选择” 的状态

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/start_b"></item>
    <item android:state_pressed="false" android:drawable="@drawable/start_a"></item>
</selector>


复选框“选中”与“不选择” 的状态

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:drawable="@drawable/check_f"></item>
    <item android:state_checked="true" android:drawable="@drawable/check_t"></item>
</selector>


你可能感兴趣的:(单选框与复选框的用法)