RT;

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="@+id/myList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>

MyActivity.java

public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/ ListView myList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList=(ListView)findViewById(R.id.myList);
BaseAdapter adapter =new BaseAdapter() {
@Override
public int getCount() {
//指定一共包含40个选项
return 40;
} @Override
public Object getItem(int i) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
//重写该方法,该方法的返回值将作为列表项的ID
@Override
public long getItemId(int i) {
return i; //To change body of implemented methods use File | Settings | File Templates.
} @Override
public View getView(int i, View view, ViewGroup viewGroup) {
//创建一个LinerarLayout,并向其中添加两个组件
LinearLayout line=new LinearLayout(MyActivity.this);
line.setOrientation(0);
ImageView image=new ImageView(MyActivity.this);
image.setImageResource(R.drawable.ic_launcher);
TextView text=new TextView(MyActivity.this);
text.setText("第"+(i+1)+"个列表项");
text.setTextSize(20);
text.setTextColor(Color.RED);
line.addView(image);
line.addView(text);
//返回LinearLayout实例
return line;
}
};
myList.setAdapter(adapter);
}
}

  效果如图:

android学习笔记——利用BaseAdapter生成40个列表项-LMLPHP

创建一个BadeAdapter对象,扩展该对象需要重写如下4个方法

* getCount():该方法的返回值控制该Adapter将会包含多少个列表项。

* getItem():该方法的返回值决定第postion处的列表项的内容。

* getItemId(int i):该方法的返回值决定第postion处的列表项的ID。

* getView(int i,View view,ViewGroup viewGroup): 该方法的返回值决定第i处的列表项组件

04-26 18:09