Android控件

来源:互联网 发布:iapp源码大全 编辑:程序博客网 时间:2024/06/05 14:19

今天 学习了安卓中的一些控件,按钮(button),选择框(单选,多选),时间日期对话,今天主要分享一个多选框,多选故名思议,就是多个选择。首选在xml文件中定义几个多选选项

<?xml version="1.0" encoding="utf-8"?><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.administrator.three.MainActivity"><LinearLayout    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="vertical"    >    <CheckBox        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="游戏"        android:id="@+id/et_main_sw"        />    <CheckBox        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="跑步"        android:id="@+id/et_main_run"        />    <CheckBox        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="读书"        android:id="@+id/et_main_book"        />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="ok"        android:onClick="ok"        /></LinearLayout></LinearLayout>

用onclick事件去Java那边调在Java中将获取的Id加入list集合中在遍历

public class MaActivity extends AppCompatActivity{    CheckBox sw;    CheckBox run;    CheckBox book;    List<CheckBox> list=new ArrayList<>();    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sw=  (CheckBox) findViewById(R.id.et_main_sw);        run=  (CheckBox)  findViewById(R.id.et_main_run);        book=  (CheckBox)  findViewById(R.id.et_main_book);        list.add(sw);        list.add(run);        list.add(book);    }    public void ok(View view){        String str="";        for(CheckBox i:list){            if(i.isChecked()){                str+=i.getText().toString()+",";            }            else if("".equals(str)){                str="";            }        }        Toast t= Toast.makeText(MaActivity.this,"爱好:"+str, Toast.LENGTH_SHORT);        t.setGravity(Gravity.CENTER,0,0);     //定义图片容器        ImageView im=new     ImageView(getApplicationContext());        //加入图片        im.setImageResource(R.drawable.icon_user);        定义图片布局        LinearLayout ll=(LinearLayout) t.getView();        布局方式        ll.setOrientation(LinearLayout.HORIZONTAL);        将图片加入布局位置        ll.addView(im,0);        t.show();    }}

这就是简易的多选。

原创粉丝点击