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();
        }
    }}
  }

如果要获取父节点的某类型的节点也是如上方法,这里我封装好了,如有需要请带走

http://120.26.185.137:8080/Demo.zip

猜你喜欢

转载自blog.csdn.net/weixin_44710155/article/details/106686278
今日推荐