首页 > 解决方案 > findViewById 在 listView 中返回 null

问题描述

大家好,我从 2 天开始就开始用 java 编码,现在我遇到了一个问题,我找到了谈论这个的话题,但没有人为我提供正确的解决方案。

我试图创建一个“使用 listView 和 android BasicAdapter 的清单,所以我得到了我的行布局 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/procedure_title_text_View"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textColor="@color/black"
        android:text="@string/procedure_title_default_name"
        android:layout_marginStart="30dp"
        android:layout_marginTop="15dp"/>

    <CheckBox
        android:id="@+id/procedure_title_checkBox"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_alignBaseline="@+id/procedure_title_text_View"
        android:layout_alignParentEnd="true"/>
</RelativeLayout>

当我尝试将此行布局添加到我的列表视图时,一切正常,但是当我尝试更改此行布局的参数时,例如使用以下代码的 TextView 中的文本:

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

        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.adapter_procedure, parent, false);
        }

        ProcedureTitle currentTitle = getItem(position);
        String titleName = currentTitle.getTitle();
        boolean titleChecked = currentTitle.getChecked();

        //afficher le titre
        TextView currentTitleView = convertView.findViewById(R.id.procedure_title_text_View);
        currentTitleView.setText(titleName);

        //actualiser l'etat de la checkbox
        CheckBox currentTitleChecked = convertView.findViewById(R.id.procedure_title_checkBox);
        currentTitleChecked.setChecked(titleChecked);

        return convertView;
    }
}

该应用程序只是崩溃并给我这样的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.protostage2_v1, PID: 21321
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.protostage2_v1.adapter.ProcedureTitleAdapter.getView(ProcedureTitleAdapter.java:69)

所以我尝试在调试模式下运行它,我发现该行(下面)返回了一个空结果。然后找不到 TextView 并导致应用程序崩溃。

TextView currentTitleView = convertView.findViewById(R.id.procedure_title_text_View);

我真的不明白为什么会这样,当我在调试模式下查看“R.id.procedure_title_text_View”时它不为空,我正在尝试解决这个问题,如果您对如何解决它有任何想法,我会很感激你的帮助!:)

标签: javaxmlnulllayout-inflaterfindviewbyid

解决方案


推荐阅读