简体   繁体   中英

ListView with different layouts - change Text in TextView

I have a custom ListView with two elemnts.

    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();
}

Everything is working fine. But if I want to setText in TextView i get a NullPointerException.

holder.txtSoundGewaehlt.setText(sound); is working fine but holder.txtOnOff.setText("Test"); crashes.

How can I change the Text of txtOnOff?

Thanks

The assumption that will get two null convertView is wrong. You will get one null convertView, and it will probably correspond to the one that you inflate at position 0. What you can do is to put all the view's in one layout and change the visibility of the components according with the position. Another solution could be to override getViewTypeCount() and getItemViewType() , this way you can have a number of null convertView s equal to getViewTypeCount()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM