看了那么长时间的书,如果不去写一点东西,老感觉自己没有学过这门语言,所以从今天开始,每天写一点东西,记录一下自己的安卓学习!
先上图:
ListView有几个步骤:
1.准备ListView要展示的数据
2.使用一维数据或多维数据保存数据
2.创建适配器
3.将适=配器添加到ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 在整个展示中listView显示的位置 -->
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/MyListView">
</ListView>
</LinearLayout>
listView中每一项展示的视图,list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- 整个彩用线性布局,上面为标题title,下面为内容content -->
<!-- 显示列表项中的标题 -->
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
<!-- 显示列表项中的内容 -->
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
布局和页面已经写好了,下面就需要写JAVA代码了:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取listView
ListView listView = (ListView) findViewById(R.id.MyListView);
//定义数据组
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String,String>>();
//准备数据
for(int i=0;i<30;i++){
HashMap< String, String> map = new HashMap<String, String>();
map.put("title", "title: "+i);
map.put("content", "this is "+i+"条内容");
mylist.add(map);
}
//创建适配器,并将数据添加到适配器中
SimpleAdapter simpleAdapter = new SimpleAdapter(this, mylist, R.layout.list_item, new String[]{"title","content"}, new int[]{R.id.title,R.id.content});
//将适配器添加到listView中
listView.setAdapter(simpleAdapter);
}
这次在开发中,在list_item.xml中以为里面放的是ListView,导致运行的时候,一直会报适配器的错误,后来才发现是自己的理解错误,list_item是用来定义ListView中的每一项内容的单个布局的,里面的内容可以是文本也可以是图片。
感悟是:编程语言你看懂,并不代表你掌握了,做为一种技能,还是需要自己去亲自实践一下!
第一次写安卓的博客,平时也不太写CSDN博客,如果大家看到我的博客,欢迎互动学习,有理解不对的地方,欢迎批评指证!