Android控件

今天 学习了安卓中的一些控件,按钮(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();

    }



}

这就是简易的多选。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值