安卓控件使用系列35:ListView列表控件显示表单的使用方法2

来源:互联网 发布:wps表格怎么刷新数据 编辑:程序博客网 时间:2024/05/22 18:35

在安卓的应用程序中经常有显示表单的功能,下面我们将这样的使用方法分享给大家。

这个例子实现的是也手机屏幕上显示三个标题对应的表单,表单中显示相应的数据列表。

整体思路:在xml文件中添加一个LinearLayout布局,在里面添加三个TextView控件,给这三个TextView控件添加文字,再添加一个ListView控件;新建一个java类MyDataSource,在这个类中定义一个getMaps方法返回一个Map类型的动态数组,里面存放三条对应TextView文字的数据,在活动中定义一个SimpleAdapter(简单适配器)类对象,用TextView的文字和对应的TextView控件ID实例化这个SimpleAdapter类对象,并把这个类对象绑定到ListView控件上。

activity_main.xml文件:

 <LinearLayout        android:layout_width="match_parent"       android:layout_height="wrap_content"       android:orientation="horizontal"       >       <TextView            android:id="@+id/pname"           android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_marginLeft="3dp"           android:layout_weight="1"           android:text="产品名称"           android:textSize="15sp"           />       <TextView            android:id="@+id/price"           android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_marginLeft="3dp"           android:layout_weight="1"           android:text="产品价格"           android:textSize="15sp"           />       <TextView            android:id="@+id/address"           android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_marginLeft="3dp"           android:layout_weight="1"           android:text="产品产地"           android:textSize="15sp"           />   </LinearLayout>   <ListView        android:id="@+id/listview"       android:layout_width="match_parent"       android:layout_height="wrap_content"       ></ListView>
MainActivity.java文件:

    private ListView listView;    private SimpleAdapter adapter;    private List<Map<String, String>> data=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView=(ListView)findViewById(R.id.listview);data=MyDataSource.getMaps();adapter=new SimpleAdapter(MainActivity.this, data, R.layout.activity_main, new String[]{"pname","price","address"}, new int[]{R.id.pname,R.id.price,R.id.address});listView.setAdapter(adapter);}

MyDataSource.java文件:

public class MyDataSource {public MyDataSource() {// TODO Auto-generated constructor stub}    public static List<Map<String, String>> getMaps(){List<Map<String, String>> listMaps=new ArrayList<Map<String,String>>();Map<String, String> map1=new HashMap<String, String>();map1.put("pname", "椰子");//Map相当于键值对数组map1.put("price", "¥23.30");map1.put("address", "海南");Map<String, String> map2=new HashMap<String, String>();map2.put("pname", "芒果");map2.put("price", "¥7.20");map2.put("address", "菲律宾");Map<String, String> map3=new HashMap<String, String>();map3.put("pname", "橙子");map3.put("price", "¥6.80");map3.put("address", "成都");listMaps.add(map1);listMaps.add(map2);listMaps.add(map3);return listMaps;}}




0 0
原创粉丝点击