基于BaseAdapter 实现ListView


注意扩展BaseAdapter 需要重写以下四个方法

getCount();

getItem();

getItemId();

getView();


程序清单

packagexiaocool.net.listviewtest;importandroid.graphics.Color;importandroid.os.Bundle;importandroid.support.v7.app.ActionBarActivity;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.BaseAdapter;importandroid.widget.ImageView;importandroid.widget.LinearLayout;importandroid.widget.ListView;importandroid.widget.TextView;publicclassMainActivityextendsActionBarActivity{privateListViewlist;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.listview2);list=(ListView)this.findViewById(R.id.list1);/*//定义一个数组Stringarr[]={"校酷网络1","校酷网络2","校酷网络3","校酷网络4","校酷网络5"};//将数组包装成ArrayAdapterArrayAdapter<String>adapter=newArrayAdapter<String>(this,R.layout.array_item,R.id.textView,arr);list.setAdapter(adapter);*/BaseAdapteradapter=newBaseAdapter(){//返回总的列表项数@OverridepublicintgetCount(){return20;}@OverridepublicObjectgetItem(intposition){returnnull;}//返回列表项的id@OverridepubliclonggetItemId(intposition){return0;}//返回每个具体item的样子@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//创建一个LinearLayout,并向其中添加两个控件LinearLayoutlayout=newLinearLayout(MainActivity.this);layout.setOrientation(0);ImageViewp_w_picpathView=newImageView(MainActivity.this);p_w_picpathView.setImageResource(R.drawable.syudio);TextViewtextView=newTextView(MainActivity.this);textView.setText("第"+(position+1)+"项");textView.setTextColor(Color.BLUE);textView.setTextSize(20);layout.addView(p_w_picpathView);layout.addView(textView);returnlayout;}};list.setAdapter(adapter);}}