ListView的滾動速度的提高在于getView方法的實現,通常我們的getView方法會這樣寫(至少我剛開始是這么寫的):
View getView(int position,View convertView,ViewGroup parent){ //首先構建LayoutInflater LayoutInflater factory = LayoutInflater.from(context); View view = factory.inflate(R.layout.id,null); //然后構建自己需要的組件 TextView text = (TextView) view.findViewById(R.id.textid); . . . return view; } 這樣ListView的滾動速度其實是最慢的,因為adapter每次加載的時候都要重新構建LayoutInflater和所有你的組件。而下面的方法是相對比較好的: View getView(int position,View contertView,ViewGroup parent){ //如果convertView為空,初始化convertView if(convertView == null){ LayoutInflater factory = LayoutInfater.from(context); convertView = factory.inflate(R.layout.id,null); } //然后定義你的組件 (TextView) convertView.findViewById(R.id.textid) ; return convertView; } 這樣做的好處就是不用每次都重新構建convertView,基本上只有在加載第一個item時會創建convertView,這樣就提高了adapter的加載速度,從而提高了ListView的滾動速度。而下面這種方法則是最好的: //首先定義一個你 用到的組件的類: static class ViewClass{ TextView textView; . . . } View getView(int position,View convertView,ViewGroup parent){ ViewClass view ; if(convertView == null){ LayoutInflater factory = LayoutInflater.from(context); convertView = factory.inflate(R.layout.id,null); view = new ViewClass(); view.textView = (TextView) convertView.findViewById(R.id.textViewid); . . . convertView.setTag(view); }else{ view =(ViewClass) convertView.getTag(); } //然后做一些自己想要的處理,這樣就大大提高了adapter的加載速度,從而大大提高了ListView的滾動速度問題。 } |
|