当前位置: 移动技术网 > IT编程>移动开发>Android > Android中通过数组资源文件xml与适配器两种方式给ListView列表视图设置数据源

Android中通过数组资源文件xml与适配器两种方式给ListView列表视图设置数据源

2020年01月08日  | 移动技术网IT编程  | 我要评论

飞跃死城,地下17000米,和尚卖艺

场景

实现效果如下

 

 

注:

博客:

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

将布局改为linearlayout,并通过android:orientation="vertical">设置为垂直布局,然后添加id属性。

然后在res下values下新建arrays.xml,数组资源文件,用来存储listview的选项内容

 

 

arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="ctype">
        <item>全部</item>
        <item>公众号</item>
        <item>霸道</item>
        <item>的</item>
        <item>程序猿</item>
        <item>博客</item>
        <item>霸道</item>
        <item>流氓</item>
        <item>气质</item>
    </string-array>
</resources>

只要通过name属性赋值为ctype,后续被引用。

然后再回到activity_list_view.xml中,通过

android:entries="@array/ctype"

为listview设置选项数组内容。

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".listviewactivity">

    <listview
        android:id="@+id/listview"
        android:entries="@array/ctype"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</linearlayout>

如果不想用这种资源文件的方式,想在代码中进行赋值,将entries属性去掉,来到activity中

首先声明一个string数组,然后声明一个适配器,并获取listview,最后将适配器与listview绑定

package com.badao.relativelayouttest;

import androidx.appcompat.app.appcompatactivity;

import android.os.bundle;
import android.widget.arrayadapter;
import android.widget.listview;

public class listviewactivity extends appcompatactivity {

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_list_view);
        //声明数组
        string[] ctype = new string[]{"全部", "公众号", "霸道的程序猿", "博客", "霸道流氓气质"};
        //声明适配器
        arrayadapter<string> adapter = new arrayadapter<string>(this, android.r.layout.simple_list_item_1, ctype);
        //获取listview
        listview listview = (listview) findviewbyid(r.id.listview);
        //关联适配器与listview
        listview.setadapter(adapter);
    }
}

效果

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网