用于展示大量数据,ListView允许用户上下滑动的方式将屏幕内未显示的内容滚动显示出来
①在布局中加入ListView控件,将宽度和高度都设置成为match_parent,占满整个布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
②修改Main_Activity代码
ListView中显示的数据可以从数据库读取,也可以视具体情境定,
这里存在data数组里面。数组中的数据无法直接传给ListView,要通过适配器完成
详细可见这个文章,传送门:ListView三种适配器介绍ArrayListAdapter,SimpleAdapter,BaseAdapter
https://blog.csdn.net/zhj19940809/article/details/51442363
这里用ArrayAdapter实现类,通过范型来指定要适配的数据类型,然后在构造函数中吧要适配的数据传入
这里的数值为String类型存储,然后在ArrayAdapter的构造函数中依次传当前上下文,子项布局id,要适配的数据
package activitytest.example.wan.listviewtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private String[] data={"Apple","Banana","Orange","Watermelon",
"Pear","Grape","Pineapple","Strewberery","Cherry","Mango",
"Apple","Banana","Orange","Watermelon",
"Pear","Grape","Pineapple","Strewberery","Cherry","Mango"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//构造函数重载,依次传入当前上下文,子项布局id,要适配的数据
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,android.R.layout.simple_list_item_1,data);
ListView listView = (ListView)findViewById(R.id.list_view);
listView.setAdapter(adapter);//将构造好的适配器对象传入,完成listview和数据之间的关联
}
}
关于android.R.layout.simple_list_item_1可以参考下面这个文章
传送门:Android系统布局——自带的布局android.R.layout详解
https://blog.csdn.net/yangzhaomuma/article/details/49877311
运行效果如下