View.getChildAt findViewById returns NPE

View.getChildAt findViewById returns NPE

我的应用使用 RecyclerViewRecyclerView

中每一项内容的xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cvExpenses"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    card_view:cardCornerRadius="5dp"
    android:layout_margin="5dp"
    card_view:cardBackgroundColor="#009dde"
    >

    <LinearLayout
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="4dip">

        <TextView
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:visibility="gone"
            android:id="@+id/tvGuestID" />

        <TextView
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.7"
            android:id="@+id/tvGuestName"
            android:textColor="#ffffff" />

        <Switch
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            android:id="@+id/swCheckIn"
            android:clickable="true"
            android:textOff="no"
            android:textOn="yes" />

    </LinearLayout>
</android.support.v7.widget.CardView>

现在我在 RecyclerView 中获得了我想要切换它的项目的索引,所以我是这样做的:

indexOfGuestIdToCheckIn = listGuestID.indexOf(guestIdToCheckIn);
View view = rvGuestList.getChildAt(indexOfGuestIdToCheckIn);
Switch swCheckIn = (Switch) view.findViewById(R.id.swCheckIn);
swCheckIn.setChecked(true);

我认为上面的代码会在我的回收站视图中切换所选项目的开关,但它 returns NullPointerExceptionSwitch swCheckIn = (Switch) view.findViewById(R.id.swCheckIn);

如果您的视图在屏幕上不可见,则您的视图还没有膨胀 正如 this answer 所述。 link 还提供了一个有趣的解决方案,您可以查看。

对于您的情况,您应该在适配器 getView() 上跟踪您的 models/objects 内部,并通过对照您的 ID 列表和它应该具有的值来检查它是否应该被检查。

HashMap<Long, Boolean> hashMap = new HashMap<>();
// put values on hashmap

@Override
public View getView(int position, View convertView, ViewGroup parent) {

     final <OBJECT> item = getItem(position);
     Switch swCheckIn = (Switch) view.findViewById(R.id.swCheckIn);
     Boolean isChecked = hashMap.get(item.getId())
     if(isChecked != null && isChecked) {
         swCheckIn.setChecked(isChecked);
     }

}