public class MainActivity extends Activity {
String[] nameList ={"banbana","apple","orange","Watermelon","Pear","Grape"};
private ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview =(ListView)findViewById(R.id.listview);
addString();
}
private void addString(){
ArrayAdapter adapter =new ArrayAdapter(this,android.R.layout.simple_list_item_1,nameList);
listview.setAdapter(adapter);
}
}
,这里面对listview添加的设配器是用系统的,ArrayAdapter (Context context, int resource, T[] objects),三个参数,第一个是context,第二个就是资源文件的id,三单个就是object数组. 再看一下xml文件:
只有一个listview,运行程序,如下:
,如果想去掉listview的横线:
listview.setDividerHeight(0);//屏蔽掉listview的横线
listview.setDivider(null);
2.listview添加一张图片和文字
修改MainActivity.java代码如下:
public class MainActivity extends Activity {
private ListView listview;
String [] lefttitles={"个人信息","健康周报","跑步","设备管理","设置","关于"};
int [] leftImageList={R.mipmap.sliding_personal_info,R.mipmap.sliding_health_news,R.mipmap.sliding_run,
R.mipmap.sliding_device_manage,R.mipmap.sliding_setting,R.mipmap.sliding_about};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview =(ListView)findViewById(R.id.listview);
addImage();
}
private void addImage(){
listview.setAdapter(new SlidingListviewAdapter(this,lefttitles,leftImageList));
}
其中leftImageList的文件就是自己存放在mipmap下的资源文件,看下这个SlidingListciewAdapter代码:
public class SlidingListviewAdapter extends BaseAdapter {
View [] itemViews;
LayoutInflater la;
public SlidingListviewAdapter(Context c, String [] itemTitles, int [] itemImageRes){
itemViews = new View[itemTitles.length];
la=LayoutInflater.from(c);
for (int i=0; i
getCount()方法(在此适配器中所代表的数据集中的条目数),getItem(int position) (获取数据集中与指定索引对应的数据项),
getItemId(int position)(取在列表中与指定索引对应的行id),每个子项被滚动到屏幕内的时候会调用getView()方法,效果如下:
源码(ListviewDemo)