android ListView自定义用法

ListView与ArrayAdapter一起使用,ArrayAdapter为ListView提供内容(包括ListView的布局和items)

举个例子:

ListView listView;

String[] msgList = {''a","b","c","d"};

ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, R.layout.msg_item, msgList);

listView.setAdapter(adapter);


其中MainActivity是本Activity的类名.

R.Layout.msg_item是布局文件,可以自己定义布局文件来显示ListView,如我这里自定义布局文件msg_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >
    
    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left">
        <TextView
            android:id="@+id/left_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:textColor="#fff"/>
     </LinearLayout>
     
      <LinearLayout
        android:id="@+id/right_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right">
        <TextView
            android:id="@+id/right_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:textColor="#fff"/>
     </LinearLayout>
            
      
    

</LinearLayout>
msg_list为ListView提供Item,可以自定义Msg类,不局限于String类型.(List<Msg> msgList)

一般自定义Msg类型是与自定义布局文件msg_item.xml相匹配.

如你想让ListView显示item的形式为:Imageview + TextView,那么你就要定义Msg类,包含:

private int resourceImageId; //对应image的资源id;

private String msg;

然后你的adapter也要重新定义(extends ArrayAdapter<Msg>),重写getView方法:

imageview.setImageResource(Msg.resourceImageId);

textview.setText(Msg.msg);

上面是伪代码,具体实现也不难.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值