2015-09-06 104 views
-1

我是Android開發新手。我試圖使用LazyAdapter將幾個圖像加載到ListView。我將圖像存儲在可繪製文件夾中。我有四個圖像:image1.jpg,image2.jpg,image3.jpg和image4.jpg。但在ListView中,它們按以下順序排列:image1.jpg,image2.jpg,image1.jpg,image2.jpg。我試圖改變方法getItemId()和getItem(),但它沒有幫助加載ListView中的所有圖像,我仍然只看到其中兩個。我無法理解我做錯了什麼。請參考我的代碼Android。 LazyAdapter加載圖像不正確

public class MainActivityFragment extends Fragment { 

CustomAdapter imagesAdapter; 

public MainActivityFragment() { 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    int[] images = {R.drawable.image1, 
      R.drawable.image2, 
      R.drawable.image3, 
      R.drawable.image4}; 

    imagesAdapter = new CustomAdapter(getActivity(), images); 

    View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
    ListView listView = (ListView) rootView.findViewById(R.id.listView); 
    listView.setAdapter(imagesAdapter); 

    return rootView; 
} 
} 

這裏是我的LazyAdapter:

public class CustomAdapter extends BaseAdapter { 

LayoutInflater inflater; 
int[] imagePaths; 

public CustomAdapter(Activity activity, int[] data) { 
    imagePaths = data; 
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public int getCount() { 
    return imagePaths.length; 
} 

@Override 
public Object getItem(int position) { 
    return position; 
} 

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

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

    View view = convertView; 

    if(view == null) { 

     view = inflater.inflate(R.layout.list_view_item, parent, false); 
     ImageView imageView = (ImageView) view.findViewById(R.id.imageView); 
     imageView.setImageResource(imagePaths[position]); 
    } 

    return view; 
} 

} 

請指點。如何使我的代碼正常工作(即在ListView中顯示所有圖像,而不僅是其中的兩個)?

+0

移動線'imageView.setImageResource(imagePaths [位置]);的'外'if'子句將圖像正確設置到行中。 – Luksprog

回答

0

您會收到此行爲,因爲listview是以重用項目的方式設計的。

@Override 

公共查看getView(INT位置,查看convertView,ViewGroup以及母公司){

View view = convertView; 

if(view == null) { 

    view = inflater.inflate(R.layout.list_view_item, parent, false); 
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView); 
    imageView.setImageResource(imagePaths[position]); 
} 

return view; 

}

此代碼解釋了這一點。只有在視圖爲空時才創建視圖,否則將重新使用已創建的視圖。

對於您的情況,對於項目1和2,視圖爲空以便適配器創建新視圖並正確設置圖像資源,但是當您向下滾動到項目3和4時,適配器正在使用已創建的視圖,所以它會顯示以前的圖像。正如LuksProg所建議的那樣,您需要將setImageResource方法移動到if子句之外,以便即使在重用視圖時,也會使用新的正確圖像更新它。

@Override 

公共視圖getView(INT位置,查看convertView,父的ViewGroup){

View view = convertView; 

if(view == null) { 

    view = inflater.inflate(R.layout.list_view_item, parent, false); 
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView); 
} 

    imageView.setImageResource(imagePaths[position]); 

return view; 

}

相關問題