如何使BaseAdapter工作

时间:2013-05-06 04:40:20

标签: android baseadapter

我正在尝试制作类别列表视图。我希望使用我的代码易于理解和使用

我有一个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。有人可以解雇我吗?

1 个答案:

答案 0 :(得分:2)

可能是由于

notifyDataSetChanged();

您在addItemaddSeparatorItem中呼叫,而无需在列表视图中设置适配器。

尝试更改您的:

public MyCustomAdapter(Context c) {
    this.context = c;
    mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}

为:

public MyCustomAdapter(Context c) {
    this.context = c;
    mInflater =LayoutInflater.from(getContext());
}