listview是Android开发中最为常见的控件,也是Android开发人员必须要掌握的控件之一,本文将用系统自定义的simpleAdapter来对我们需要的布局进行一些填充和修改。现在我们先上一张效果图。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view); //实例化listview
/**
SimpleAdapter类中我们要传入几个参数。1、上下文对象 2、List<Map<String,Object>>对象
3、传入参数的页面布局 4、字符串数组 5、参数地址值。
*/
SimpleAdapter adapter = new SimpleAdapter(this,get(),R.layout.item,
new String[]{"第一行","第二行"},
new int[]{R.id.item1,R.id.item2});
listView.setAdapter(adapter);
}
private List<Map<String,Object>> get(){
/**
创建ArrayList<Map<String, Object>>()对象,最后new ArrayList<Map<String, Object>>()。
在新的版本中new ArrayList<Map<String, Object>>()可以直接写成new ArrayList<>()。
Put()方法中就可以放我们想要的对象,最后通过add()添加。除此之外,
put()方法中还可以添加图片,这里就不一一描述了。
*/
List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
Map<String,Object> map = new ArrayList<Map<String, Object>>();
map.put("第一行","这是第一行");
map.put("第二行","这是第2行");
list.add(map);
map = new HashMap<String,Object>();
map.put("第一行","这是第一行");
map.put("第二行","这是第2行");
list.add(map);
return list;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!--主活动界面,activity_main-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<!--item界面,主要用来展示listview上面的数据-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/item1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第一行"/>
<TextView
android:id="@+id/item2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第er行"/>
</LinearLayout>