首页 > 解决方案 > ListView 获取所有子视图(在屏幕上和屏幕外)

问题描述

我正在尝试迭代列表视图的所有子视图,包括那些不在屏幕上的子视图(在滚动之前不可见),但它只返回那些在屏幕上的子视图(可见)。

Button btnAddToCart = (Button) findViewById(R.id.btnAddToCart);
    btnAddToCart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            View view;
            TextView tvProductBrand;
            for (int i = 0; i < lv.getCount(); i++){

                view = lv.getChildAt(i);
                if(view != null)
                {
                    tvProductBrand = (TextView) view.findViewById(R.id.tvProductBrand);
                    str_ItemBrand_from_lv = tvProductBrand.getText().toString();

                    Toast.makeText(getApplicationContext(), "lv_item: "+str_ItemBrand_from_lv, Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

我知道view = lv.getChildAt(i);这只返回可见视图,我怎样才能返回所有子视图?

我的 listview 适配器是lv_custom_adapter(也许我需要使用它,但不确定如何)?

标签: android

解决方案


使用RecyclerView是个好主意

梯度依赖:

implementation "com.android.support:recyclerview-v7:28.0.0"

https://developer.android.com/guide/topics/ui/layout/recyclerview

把它放在NestedScrollView 集合中nestedScrollingEnabled=true

<NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:nestedScrollingEnabled="true"/>

您将立即获得所有孩子


推荐阅读