我正在尝试创建一个可扩展的列表视图,其中每个列表的最后一项包含EditText,其他项包含TextViews。我到目前为止的代码:
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
MainActivity.ViewHolder holder = null;
final String childText = (String) getChild(groupPosition, childPosition);
boolean bLastChild = childPosition == _listDataChild.get(groupPosition).size() - 1;
if (convertView == null) {
holder = new MainActivity.ViewHolder();
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(bLastChild) {
convertView = infalInflater.inflate(R.layout.list_edit_item, null);
}else {
convertView = infalInflater.inflate(R.layout.list_item, null);
holder.textView = (TextView) convertView.findViewById(R.id.text);
}
convertView.setTag(holder);
} else {
holder = (MainActivity.ViewHolder)convertView.getTag();
}
if(!bLastChild) {
holder.textView.setText(childText);
}
return convertView;
}
现在我遇到以下问题:
如果我第一次扩展群组。但是当我崩溃组并再次扩展它时,应用程序崩溃了,我得到了错误:
java.lang.NullPointerException:尝试调用虚方法' void android.widget.TextView.setText(java.lang.CharSequence中)'在null 对象参考
我想这是因为当持有者使用EditText引用布局时调用holder.textView.setText(childText);
。但我不知道为什么会发生这种情况
此代码的主要思想来自here
修改
经过一些日志记录后我发现,第二次扩展组时,每个孩子都会调用一次getChildView,然后在childPosition = 0时调用一次,但convertView与上一个子位置的调用保持一致:< / p>
childPosition:0; convertView:android.widget.LinearLayout {a049868 V.E ...... ........ 0,157-1080,244} childPosition 1; convertView:android.widget.LinearLayout {6f19175 V.E ...... ........ 0,247-1080,334} childPosition 2; convertView:android.widget.LinearLayout {4aac50a V.E ...... ........ 0,337-1080,424} childPosition 3; convertView:android.widget.LinearLayout {47b217b V.E ...... ........ 0,427-1080,514} childPosition 4; convertView:android.widget.LinearLayout {cc2eb98 V.E ...... ........ 0,517-1080,604} childPosition 5; convertView:android.widget.LinearLayout {256cff1 V.E ...... ........ 0,607-1080,694} childPosition 6; convertView:android.widget.LinearLayout {7b827d6 V.E ...... ........ 0,697-1080,786} childPosition 0; convertView:android.widget.LinearLayout {7b827d6 V.E ...... ........ 0,697-1080,786}
答案 0 :(得分:0)
通过重写以下两个函数来解决问题:
@Override
public int getChildTypeCount(){
return 2;
}
@Override
public int getChildType(final int groupPosition, final int childPosition){
if (childPosition == _listDataChild.get(groupPosition).size() - 1){
return 1;
}else{
return 0;
}
}