我正在尝试制作类别 listview 。我想使用我的代码易于理解和使用
我有一个 MainActivity 类
public class MainActivity extends Activity{
private MyCustomAdapter mAdapter;
ListView lst;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lst = (ListView)findViewById(R.id.lstView);
mAdapter = new MyCustomAdapter(this);
for (int i = 1; i < 50; i++) {
mAdapter.addItem("Sameer Blog " + i);
if (i % 4 == 0) {
mAdapter.addSeparatorItem("Ahmad " + i);
}
}
lst.setAdapter(mAdapter);
}
}
和这样的 MyCustomAdapter 类
public class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private Context context;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context c) {
this.context = c;
mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public String getItem(int position) {
return mData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView txtView = null;
int type = getItemViewType(position);
if (convertView == null) {
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.list_item, null);
txtView = (TextView)convertView.findViewById(R.id.txtItem);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.list_header, null);
txtView = (TextView)convertView.findViewById(R.id.txtHeader);
break;
}
}
txtView.setText(mData.get(position));
return convertView;
}
}
但我总是在 logcat 中得到 NullPointerException 。有人可以帮我吗???