Android_03_ArrayAdapter的使用

来源:互联网 发布:win10 补丁安装软件 编辑:程序博客网 时间:2024/06/16 05:54

MainActivity.java

package com.example.arrayadapter;import android.app.Activity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);String[] objects = new String[]{"jack","will","smith"};ListView lv = (ListView) findViewById(R.id.lv);//ArrayAdapter只能显示一种类型的对象lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv, objects));}}
</pre><p><strong><span style="font-size:12px; color:#ff0000">注:</span></strong>关于ArrayAdapter<T>(context, resource, textViewResourceId, objects)中参数的解释:</p><p>T:表示每个列表项中,你要放的数据的类型</p><p>context:表示上下文,它代表了访问整个Android应用的接口</p><p>resource:你的布局文件的id  ,这个布局文件里边存放的布局就是ListView中每个列表项的布局</p><p>textViewResourceId :TextView的资源id</p><p>objects:  表示你要往每个列表项放入的数据</p><p></p><p><strong><span style="color:#ff0000">注:</span></strong>ArrayAdapter的优点就是使用方便,缺点是每个列表项只能是TextView</p><p></p><p><strong><span style="font-size:12px; color:#ff0000">activity_main.xml</span></strong></p><p></p><p></p><pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <ListView        android:id="@+id/lv"        android:layout_width="match_parent"        android:layout_height="wrap_content"                /></LinearLayout>

item_listview.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="wrap_content"    android:orientation="horizontal" >        <ImageView        android:id="@+id/iv"         android:layout_width="50dp"        android:layout_height="50dp"        android:src="@drawable/photo_2"                />    <TextView         android:id="@+id/tv"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:textSize="25sp"        android:gravity="center_vertical"        android:textColor="#ff99cc00"        />    </LinearLayout>

实际效果如下:




0 0