2014-09-18 2 views
-1

두 개의 elemnt가있는 사용자 지정 ListView가 있습니다.다른 레이아웃이있는 ListView - TextView의 텍스트 변경

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에서 텍스트를 설정하려면 NullPointerException이 발생합니다.

holder.txtSoundGewaehlt.setText (사운드); 잘 작동하지만 holder.txtOnOff.setText ("Test"); 충돌.

어떻게 txtOnOff의 텍스트를 변경할 수 있습니까?

감사

+1

당신이 getItemViewType (위치)를 사용하여 수행해야합니다 null로 convertView의 동일한의 번호를 가질 수 getViewTypeCount()getItemViewType(),이 방법을 대체 할 수 있었다! –

답변

3

이 널 (null) convertView이 잘못 얻을 것이다 가정. 하나의 null convertView가 생기고 위치 0에서 팽창시킨 것과 일치 할 것입니다. 모든 뷰를 하나의 레이아웃에 배치하고 위치에 따라 구성 요소의 가시성을 변경하는 것입니다. 또 다른 해결책은 당신이 getViewTypeCount()

+0

아니요, 올바른 방법으로이 예제에서와 같이 getViewTypeCount()를 사용하십시오. http : //stackoverflow.com/questions/4777272/android-listview-with-different-layout-for-each-row – Decoy

+0

끝내고 있습니다. 내 대답을 편집하십시오. 아직도, 제 의견으로는 2 개의 요소에 대해서만 그 메소드를 오버라이드하는 것은 이해가되지 않습니다 @Decoy – Blackbelt

+0

코드가 훨씬 더 명확하고 이해할 수있는 얼마나 많은 다른 뷰와도 상관 없습니다 ... – Decoy

관련 문제