安卓课程二十 CheckBox复选框控件使用
16lz
2021-01-23
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) ;}@Overridepublic 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() ;}}
更多相关文章
- Android Studio:在xml布局中不能自动补全代码
- android 改变系统默认动态壁纸
- Android——UI篇:动态设置DiaLog高度
- Android动态加载——加载未安装APK中的类&加载已安装APK中的类和
- 自定义android Intent Action与继承TextView形成一个动态改变tex
- Android纯代码写布局
- android 系统提示对话框(AlertDialog)的使用
- 【Android 性能优化】布局渲染优化 ( GPU 过度绘制优化总结 | CP
- 提示服务Notification在Android中的应用