0

我正在尝试在选项卡中实现列表视图。我正在使用自定义 arrayadapter 创建自定义列表视图。代码如下。

创建选项卡活动:

TabHost th = getTabHost();
TabSpec specGroups = th.newTabSpec("Groups");
    specGroups.setIndicator("Groups");
    Intent intentGroups = new Intent(this, GroupsList.class);
    specGroups.setContent(intentGroups);

群列表活动:

public class GroupsList extends Activity {

public String[] ROSTER_LIST = {"Sam", "Bob", "Tabg", "Toushi", "john"};
private ListView ROSTER_LISTVIEW;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.groups_list);

    Log.d("STARTED", "0");

    ROSTER_LISTVIEW = (ListView) findViewById(R.id.listViewFriends);
    Log.d("STARTED", "1");

    ArrayAdapter<String> adapter = new MyAdapter(this,
            android.R.layout.simple_list_item_1, R.id.textViewRosterRow,
            ROSTER_LIST);
    Log.d("STARTED", "2");

    ROSTER_LISTVIEW.setAdapter(adapter);
    Log.d("STARTED", "3");

}

自定义适配器类(内部类):

private class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] ROSTER_LIST) {
        super(context, resource, textViewResourceId, ROSTER_LIST);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Log.d("ADAPTER", "0");
        View row = inflater
                .inflate(R.layout.friends_list_row, parent, false);
        Log.d("ADAPTER", "1");

        TextView text = (TextView) row.findViewById(R.id.textViewRosterRow);
        Log.d("ADAPTER", "2");
        text.setText(ROSTER_LIST[position]);

        Log.d("ADAPTER", "OK");
        return row;
    }

}

在 oncreate 方法Log.d("STARTED", "2");行中登录 logcat,然后弹出 nullpointerexception。内部类Log内部的 logcat 中没有日志。MyAdapter

此代码在没有选项卡的情况下可以正常执行。

我在这里犯了什么错误?我该如何解决这个问题?提前致谢 :)

4

1 回答 1

0

将适配器 getView 更改为:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;

        if(row==null){
          LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          Log.d("ADAPTER", "0");
          row = inflater
                .inflate(R.layout.friends_list_row, parent, false);
          Log.d("ADAPTER", "1");
      }
        TextView text = (TextView) row.findViewById(R.id.textViewRosterRow);
        Log.d("ADAPTER", "2");
        text.setText(ROSTER_LIST[position]);

        Log.d("ADAPTER", "OK");
        return row;
    }
于 2012-10-13T03:05:11.960 回答