天才就是百分之九十九的汗水加百分之一的灵感。
本讲内容:CheckBox 选择框
我们也是使用一个例子来演示选择框,请在这里例子里留意 onClickListener和onCheckedChangeListener的区别
示例一:
下面是res/layout/activity_main.xml 布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.text.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择你喜欢的人:" />
<CheckBox
android:id="@+id/checkBoxId1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="得不到"/>
<CheckBox
android:id="@+id/checkBoxId2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="已失去"/>
</LinearLayout>
android:checked="false" 默认的,true设置选中
下面是主文件:
public class MainActivity extends Activity {
private CheckBox checkBox1;
private CheckBox checkBox2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBox1 = (CheckBox) findViewById(R.id.checkBoxId1);
checkBox2 = (CheckBox) findViewById(R.id.checkBoxId2);
OnListener1 listener1=new OnListener1();
OnListener2 listener2=new OnListener2();
checkBox1.setOnClickListener(listener1);
checkBox2.setOnClickListener(listener1);
checkBox1.setOnCheckedChangeListener(listener2);
checkBox2.setOnCheckedChangeListener(listener2);
}
class OnListener1 implements OnClickListener {
@Override
public void onClick(View v) {
if (!((CheckBox) v).isChecked()) {
Toast.makeText(MainActivity.this,
"\"" + ((TextView) v).getText() + "\"被取消",Toast.LENGTH_SHORT).show();
}
}
}
class OnListener2 implements OnCheckedChangeListener {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked) {// isChecked=true
Toast.makeText(MainActivity.this,"\"" + buttonView.getText() + "\"被选择",Toast.LENGTH_SHORT).show();
}
}
}
}
onClickListener和onCheckedChangeListener的区别:onCheckedChangeListener有参数 isChecked直接使用,而onClickListener需向下转型,继承CheckBok的isChecked()方法
Take your time and enjoy it