自定義 BaseAdapter 中 getView() 設置 TextView 文字時拋出 NullPointerException,日誌提示 findViewById(R.id.textView2) 返回 null。
// 原有問題代碼片段
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
View customView = arg1;
ViewHolder holder;
if (arg1 == null) {
customView = inflater.inflate(R.layout.listrow, null); // 錯誤:未傳入 parent
holder = new ViewHolder();
holder.tv = (TextView) customView.findViewById(R.id.textView2);
// 缺失:customView.setTag(holder);
} else {
holder = (ViewHolder) customView.getTag(); // 因未 setTag,此處取得 null
}
// ...
holder.tv.setText("" + pinfo.appname); // NPE:holder 為 null
return customView;
}
inflate(layout, null) 導致佈局參數失效,子視圖尺寸異常setTag(holder):convertView 複用時無法取回 ViewHolder,導致重複 findViewById 或 holder 為 null@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
// 正確:傳入 parent,attachToRoot=false
convertView = inflater.inflate(R.layout.listrow, parent, false);
holder = new ViewHolder();
holder.iv = convertView.findViewById(R.id.imageView1);
holder.tv = convertView.findViewById(R.id.textView2);
holder.cb = convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder); // 關鍵:綁定 holder
} else {
holder = (ViewHolder) convertView.getTag();
}
PInfo pinfo = installedApps.get(position);
holder.tv.setText(pinfo.appname);
holder.iv.setImageDrawable(pinfo.icon);
// CheckBox 狀態同步邏輯...
return convertView;
}
static class ViewHolder { // static 避免記憶體洩漏
ImageView iv;
TextView tv;
CheckBox cb;
}
findViewById 與型別轉換錯誤RecyclerView,自動計算差異動畫