关于setOnCheckedChangeListener的使用

toggleButton

public class ToggleActivity extends Activity implements CompoundButton.OnCheckedChangeListener {

    private ToggleButton tb;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.toggle_layout);
        tb=(ToggleButton)findViewById(R.id.toggle);
        img=(ImageView)findViewById(R.id.image);

        //给tb监听
        tb.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        /*
        buttonView代表被点击控件的本身,isChecked代表状态
         */
        img.setBackgroundResource(isChecked? R.drawable.deng1:R.drawable.deng2);
    }
}

布局



    

CheckBox

复选框,可以有多个,而且在屏幕中选择的时候可以取消

/**
 * Checkbox的使用方法
 */
public class TestActivity extends Activity implements CompoundButton.OnCheckedChangeListener {

    private CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        checkBox=(CheckBox)findViewById(R.id.basketball);
        checkBox.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            //获得文本内容
            String text=checkBox.getText().toString();
            Log.i("tag",text);
        }
    }
}


RadioGroup/RadioButton

单选按钮集合和单选按钮,只能在集合中选择一个,且必须有一个

public class RadioGroupActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup rg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_group);
        rg.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId){
            case R.id.rd1:
                Log.i("tag","man");
                break;
            case R.id.rd2:
                Log.i("tag","female");
                break;
        }
    }
}


        
        
    



你可能感兴趣的:(Android)