ListView rows with different layouts

亡梦爱人 提交于 2019-12-02 01:00:40

That NullPointerException occurs because you didn't implement the getItemViewType. Right now you return the first type of row layout no matter what and this is a layout that doesn't have the *txtView_test* TextView). Your code should be something like this:

// some fields
public static final int FIRST_TYPE = 0;
public static final int SECOND_TYPE = 1;

@Override
public int getItemViewType(int position) {
     MyContents item = getItem(position);
     if (item.testBoolean()) {
          return FIRST_TYPE;
     } else {
          return SECOND_TYPE; 
     } 
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final MyContents entry = content.get(position);
    View row = convertView;
    LayoutInflater inflater = null;
    int type = getItemViewType(position);
    boolean _haschild_ = entry.testBoolean();
    if (row == null) {
        if (type == FIRST_TYPE) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater
                    .inflate(R.layout.contents_layout, null);
        } else {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.test_layout, null);
        }
    } 
    if (type == FIRST_TYPE) {
        TextView txtView = (TextView) row
                .findViewById(R.id.txtView);
        //.....
    } else {
        ((TextView) row.findViewById(R.id.txtView_test)) //**LOE**
                .setText("test: " + position); //**LOE**
    }

Use,

LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.test_layout, parent, false);

May it solves your problem.

Try This :::

convertView = getLayoutInflater().inflate(R.layout.my_row_layout, null);


TextView txtName = (TextView)convertView.findViewById(R.id.txtMyTextView);

txtName.setText("Hi,,,,. Hows You..."); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!