Android获取父节点的所有子节点(CheckBox的使用,本次以CheckBox为例)

在开发中我们可能会遇到需要获取父节点的某个或者所有子节点,怎么做呢,Android里边有个方法 

View.getChildAt(int index);不用我多说了吧,这个方法就是返回View节点下的第Index个节点,有了这个方法,我们就能获取到父节点的某个或者所有子节点了,下面用代码实现

首先XML文件里先放5个CheckBox(复选框),父节点为LinearLayout(id为all)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/all"
        android:orientation="vertical">
<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="1"
    ></CheckBox>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2"
        ></CheckBox>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="3"
        ></CheckBox>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="4"
        ></CheckBox>
    <CheckBox
        android:id="@+id/d5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="5"
        ></CheckBox>
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="确定"
        android:onClick="sub"
        ></Button>
</LinearLayout>

2我们可以在按钮的点击事件sub里实现获取所有子节点,然后判断复选框是否被选中

public void sub(View view){
    LinearLayout l= (LinearLayout)findViewById(R.id.all);
  CheckBox box;
    for(int i=0;i<l.getChildCount();i++){
        box=(CheckBox)l.getChildAt(i);
        if(box.isChecked()){/*判断复选框是否被选中,被选中就打印文本*/
            Toast.makeText(this, box.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    }
  }

运行结果截图:(打印了123,但是我这里只截取了3)

这是父节点里全部为同一类型的子节点时可以这么做,但是,如果父节点里不全部是同一类型的节点我们又该这么做呢?

其实我们可以判断一下就行了,比如既有CheckBox,又有Button,我们需要CheckBox,这时我们要这要做

public void sub(View view){
    LinearLayout l= (LinearLayout)findViewById(R.id.all);
  CheckBox box;
    for(int i=0;i<l.getChildCount();i++){
       if(l.getChildAt(i).indexOf("androidx.appcompat.widget.AppCompatCheckBox")>-1){
        box=(CheckBox)l.getChildAt(i);
        if(box.isChecked()){
            Toast.makeText(this, box.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    }}
  }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值