安卓课程二十 CheckBox复选框控件使用
linelayout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/buton" android:text="@string/button"> </Button> </LinearLayout>
checkbox.xml
<?xml version="1.0" encoding="utf-8"?> <CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > </CheckBox>
MainActivity.java
import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; public class MainActivity extends Activity implements OnClickListener{ private List <CheckBox> checkboxs = new ArrayList<CheckBox> (); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); String[] chekcBoxTexts = new String[]{"旅游","读书","看书","爬山","踢足球","打篮球","打乒乓球"}; //动态加载布局 LinearLayout linerLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.linelayout, null) ; for(int i=0;i< chekcBoxTexts.length;i++){ String item = chekcBoxTexts[i]; //动态创建布局 CheckBox checkbox = (CheckBox) getLayoutInflater().inflate(R.layout.checkbox, null); checkbox.setText(item); checkboxs.add(checkbox); linerLayout.addView(checkbox, i); } setContentView(linerLayout); Button button = (Button) this.findViewById(R.id.buton); button.setOnClickListener(this) ; } @Override public void onClick(View v) { StringBuffer s = new StringBuffer(); for(CheckBox box : checkboxs){ if(box.isChecked()){ if(s.length()>0){s.append("\n");} s.append(box.getText()) ; } } if(s.length()==0){ s.append("您还没有选择呢"); } //使用提示框提示用户信息 new AlertDialog.Builder(this).setMessage(s.toString()).setPositiveButton("关闭", null).show() ; } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28