首页 > 代码库 > UI控件之ListView

UI控件之ListView

一,一个简单的TextView列表

public class FirstActivity extends Activity {
    private String[] data = http://www.mamicode.com/{"Apple", "Banana", "Orange", "Watermelon",
            "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango","Apple", "Banana", "Orange", "Watermelon","Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(         //ArrayAdapter数组适配器
                FirstActivity.this, android.R.layout.simple_list_item_1, data);
      //第一个参数,上下文对象;第二个参数,一个官方的内置布局的id(这是一个TexView);第三个参数,传入的数据
        ListView listView = (ListView) findViewById(R.id.ListView);
        listView.setAdapter(adapter);
    }
}

 

二,好玩的东西怎么可以只有Text View呢(来点复杂的)

1.新建一个用于存放水果的类
public class Fruit {
    private String name;
    private int imageId;

    //构造器初始化
    public Fruit(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }
}

2.新建一个自定义的布局文件

用于描述布局方式,等待被调用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3.自定义适配器,继承于ArrayAdapter

UI控件之ListView