首页 > 代码库 > ListView的优化

ListView的优化

用convertView优化ListView

 

 1 package com.example.zhangmeng.myliestview; 2  3 import android.os.Bundle; 4 import android.support.v7.app.AppCompatActivity; 5 import android.view.View; 6 import android.view.ViewGroup; 7 import android.widget.BaseAdapter; 8 import android.widget.ListView; 9 import android.widget.TextView;10 11 public class MainActivity extends AppCompatActivity {12 13     @Override14     protected void onCreate(Bundle savedInstanceState) {15         super.onCreate(savedInstanceState);16         setContentView(R.layout.activity_main);17         ListView lv=(ListView)findViewById(R.id.lv);18         MyAdapter adapter=new MyAdapter();19         lv.setAdapter(adapter);20     }21 22     class MyAdapter extends BaseAdapter{23 24         @Override25         public int getCount() {26             return 100;27         }28 29         @Override30         public Object getItem(int position) {31             return null;32         }33 34         @Override35         public long getItemId(int position) {36             return 0;37         }38 39         @Override40         public View getView(int position, View convertView, ViewGroup parent) {41 42             TextView tv=null;43             if(convertView==null){44                 tv=new TextView(MainActivity.this);45             }46             else{47                 tv=(TextView) convertView;48             }49 50             tv.setText("Hello"+(position+1));51             return tv;52         }53     }54 }

 

ListView的优化