java - 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”时它不为空,我正在尝试解决这个问题,如果您对如何解决它有任何想法,我会很感激你的帮助!:)
解决方案
推荐阅读
- python - Python Selenium - 无法单击按钮(iFrame 已解决!)
- javascript - 在 Android 中使用 Cordova 捕获实时麦克风音频
- html - 如何强制div水平而不是垂直溢出?
- apache-spark - parquet 文件大小,firehose 与 spark
- php - 尝试访问 Microsoft Graph 时“无法获取本地颁发者证书”
- javascript - 如何使用 Jest 测试 React 组件的 onClick 行?
- python - 类型错误:
() 缺少 1 个必需的位置参数:“项目” - sql - 如果 n-1、n-2.. 结果在 n 的 30 天内,则在分区中获得第 n 个结果
- excel - 尝试用 Excel 单元格内容替换书签时出现 MS Word 自动化错误
- jquery - 通过 JQuery 检测元素上的内联样式/CSS 更改