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”时,它不为空,如果您有任何想法,我正在尝试解决问题解决它,我会很感激你的帮助! :)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...