您的位置:首页 > 其它

关于setOnCheckedChangeListener的使用

2016-08-21 19:08 357 查看
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);
}
}

布局
<ToggleButton
android:checked="false"
android:textOn="open"
android:textOff="close"
android:id="@+id/toggle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />

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);
}
}
}
<CheckBox
android:id="@+id/basketball"
android:checked="false"
android:text="篮球"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


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;
}
}
}
<RadioGroup
android:id="@+id/rg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/rd1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="man"
android:checked="true"/>
<RadioButton
android:id="@+id/rd2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="female"
android:checked="false"/>
</RadioGroup>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: