2016-04-24 106 views
0

我試圖使自定義列表視圖創建一個空對象引用

@Override 
public View getView(int i, View view, ViewGroup parent) { 
    ViewHolder viewHolder; 
    if (view == null){ 
     inflater = (LayoutInflater) context.getSystemService(Service.LAYOUT_INFLATER_SERVICE); 
     view = inflater.inflate(R.layout.cities_weather_detail, parent, false); 
     viewHolder = new ViewHolder(); 
     viewHolder.cityName = (TextView) view.findViewById(R.id.city_name); 
     Data data = citiesData.get(i); 
     viewHolder.cityName.setText(data.getCity().getName()); 
     view.setTag(viewHolder); 
    } 
    return view; 
} 
自定義列表視圖和錯誤試圖調用虛擬方法「布爾java.lang.String.equals(java.lang.Object中)」

當我嘗試訪問城市名稱viewHolder.cityname中的ID時,它正在破壞。

class ViewHolder{ 
    TextView cityName; 
    //TextView temperature; 
} 

回答

0

要創建自定義的ListViewü必須這樣做:

@Override @Override 
    public View getView(int i, View view, ViewGroup viewGroup) { 
     View vi = view; 

     if (view == null) { 
      vi = inflater.inflate(R.layout.list_item, null); 
     } 
     inflater = (LayoutInflater) context.getSystemService(Service.LAYOUT_INFLATER_SERVICE); 

     TextView cityName = (TextView) vi.findViewById(R.id.city_name); 
     Data data = citiesData.get(i); 
     cityName.setText(data.getCity().getName()); 


     return vi; 
0

這不是你就行了NPE一個驚喜:

viewHolder.cityName =(TextView中) view.findViewById(R.id.city_name);

因爲2行以上,你正在測試那個視圖 null。

你缺少的視圖的創建:

視圖= inflater.inflate(R.layout.YOUR_LAYOUT,父母,假);

0

你忘了做什麼,如果視圖不是空

添加以下代碼。

@Override 
    public View getView(int i, View view, ViewGroup parent) { 
     ViewHolder viewHolder; 
     if (view == null){ 
      inflater = (LayoutInflater) context.getSystemService(Service.LAYOUT_INFLATER_SERVICE); 
      view = inflater.inflate(R.layout.cities_weather_detail, parent, false); 
      viewHolder = new ViewHolder(); 
viewHolder.cityName = (TextView) view.findViewById(R.id.city_name); 
      view.setTag(viewHolder); 
     } 
    else 

    {viewHolder = (ViewHolder) view.getTag(); 

    } 

      Data data = citiesData.get(i); 
      viewHolder.cityName.setText(data.getCity().getName()); 
     return view; 
    } 

如有任何疑問,請隨時詢問。