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

场景

实现效果如下

813a23c1f0a5900e6bc7c2c903143afc.png

84453.html

注:

实现

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

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

arrays.xml:

全部

公众号

霸道

程序猿

博客

霸道

流氓

气质

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

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

android:entries="@array/ctype"

为listView设置选项数组内容。

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

如果不想用这种资源文件的方式,想在代码中进行赋值,将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 classListViewActivity extends AppCompatActivity {

@Overrideprotected voidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_list_view);//声明数组

String[] ctype = new String[]{"全部", "公众号", "霸道的程序猿", "博客", "霸道流氓气质"};//声明适配器

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, ctype);//获取listView

ListView listView =(ListView) findViewById(R.id.listView);//关联适配器与listView

listView.setAdapter(adapter);

}

}

效果

b050930001e434a0836fd06cf4b3f0fd.png

84453.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值