【发布时间】:2014-01-22 13:03:25
【问题描述】:
我找到了这 2 个答案:https://stackoverflow.com/a/11787066/1489990 和 https://stackoverflow.com/a/18868395/1489990,我一直在尝试遵循这些答案来完成每个项目具有不同布局的列表视图。我的数组适配器如下所示:
public class MyArrayAdapter<T> extends ArrayAdapter<T> {
LayoutInflater mInflater;
int[] mLayoutResourceIds;
public MyArrayAdapter(Context context, int[] textViewResourceId, List<T> objects) {
super(context, textViewResourceId[0], objects);
mInflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
mLayoutResourceIds = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = null;
int type = getItemViewType(position);
// instead of if else you can use a case
if (row == null) {
if (type == TYPE_ITEM1) {
//infalte layout of type1
row = inflater.inflate(R.id.item1, parent, false); //*****************
}
if (type == TYPE_ITEM2) {
//infalte layout of type2
} else {
//infalte layout of normaltype
}
}
return super.getView(position, convertView, parent);
}
@Override
public int getItemViewType(int position) {
if (position== 0){
type = TYPE_ITEM1;
} else if (position == 1){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type; //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public int getViewTypeCount() {
return 3; //To change body of overridden methods use File | Settings | File Templates.
}
}
还有我的 onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array = new String[] {"one", "two", "three", "four", "five", "six"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, array);
ListView listView = new ListView(this);
listView.setAdapter(new MyArrayAdapter<String>(this, new int[] {android.R.layout.simple_list_item_1, android.R.layout.simple_list_item_single_choice}, list));
setContentView(listView);
}
这个问题是我的数组适配器中的行:
row = inflater.inflate(R.id.item1, parent, false);
给出错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean)' on a null object reference
我对 xml 布局的结构有点困惑。现在我有 1 个用于 listView 的 xml 和一个用于第一个列表布局的单独的 xml,我尝试在 1 个 xml 布局中制作它,但它仍然给出了空指针异常。我需要一些关于如何实现这一点的指导。谢谢
【问题讨论】: