具有不同布局的ListView - 在TextView中更改文本

时间:2014-09-18 14:18:37

标签: android listview android-custom-view baseadapter

我有一个带有两个元素的自定义ListView。

    Context mContext;
LayoutInflater inflater;
String sound;
Boolean vibrate;

public BenachrichtigungLVAdapter(Context context, String sound, Boolean vibrate) {
    mContext = context;
    inflater = LayoutInflater.from(mContext);
    this.sound = sound;
    this.vibrate = vibrate;
}

public class ViewHolder {
    TextView txtSoundWaehlen;
    TextView txtSoundGewaehlt;
    TextView txtVibrationTV;
    TextView txtOnOff;
}


@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder = null;
    holder = new ViewHolder();
    if (view == null) {
        switch (position) {
        case 0:
            view = inflater.inflate(R.layout.soundsingle, null);
            holder.txtSoundWaehlen = (TextView) view.findViewById(R.id.Soundwaehlen);
            holder.txtSoundGewaehlt = (TextView) view.findViewById(R.id.selectedSound);
            break;
        case 1:
            view = inflater.inflate(R.layout.vibrationsingle, null);
            holder.txtVibrationTV = (TextView) view.findViewById(R.id.VibrationTV);
            holder.txtOnOff = (TextView) view.findViewById(R.id.OnOffTV);
            break;
        }
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    if(position == 0){
        holder.txtSoundGewaehlt.setText(sound);
    } else if(position == 1){
        holder.txtOnOff.setText("Test");
    }

    return view;
}

@Override
public int getCount() {
    // TODO Automatisch generierter Methodenstub
    return 2;
}

@Override
public Object getItem(int position) {
    // TODO Automatisch generierter Methodenstub
    return null;
}

public void setSound(String sound){
    this.sound = sound;
    notifyDataSetChanged();
}

一切都很好。但是如果我想在TextView中使用setText,我会得到一个NullPointerException。

holder.txtSoundGewaehlt.setText(声音);工作正常但是 holder.txtOnOff.setText( “测试”);崩溃。

如何更改txtOnOff的文本?

由于

1 个答案:

答案 0 :(得分:3)

假设将获得两个空convertView是错误的。您将得到一个null convertView,它可能对应于您在位置0膨胀的那个。您可以做的是将所有视图放在一个布局中并根据位置更改组件的可见性。另一种解决方案可能是覆盖getViewTypeCount()getItemViewType(),这样您就可以拥有一些等于convertView的空getViewTypeCount()