在 Android 中使用 ListView 显示数据

先说两个用于布局的属性:

match_parent 和 wrap_content,另有一个 fill_parent 与 match_parent 相同

match_parent表示当前控件的大小和父布局一样,也就是说大小由上层布局控制;wrap_content表示让控件的大小可以包含里面的内容,也就是说大小是动态的,由内容的多少控制大小。

一、控件的放置

打开对应的页面,显示如下图:

image-20211122215058756

选择需要删除的控件,在上面按右键,使用删除就可以了,另外,将约束布局改为相对布局,放入 ListView 控件,改 ID 为 list_view 用于演示。更改完成后如下图:

image-20211122221938622

从 Text 中查看 xml 代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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">
    <ListView        android:id="@+id/list_view"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></RelativeLayout>

二、关联代码

打开 java 文件,其中有系统自动生成的代码,屏蔽掉不使用的部分,加入运行所需要的,改完如下图:

public class NotificationsFragment extends Fragment {
    private NotificationsViewModel notificationsViewModel;
    private String[] data = {"apple", "orange", "blue", "black", "green"};
    public View onCreateView(@NonNull LayoutInflater inflater,                             ViewGroup container, Bundle savedInstanceState) {        notificationsViewModel =                ViewModelProviders.of(this).get(NotificationsViewModel.class);        View root = inflater.inflate(R.layout.fragment_notifications, container, false);
        ArrayAdapter adapter = new ArrayAdapter&lt;String&gt;(container.getContext(),                android.R.layout.simple_list_item_1, data);        ListView listView = (ListView)root.findViewById(R.id.list_view);        listView.setAdapter(adapter);
//        final TextView textView = root.findViewById(R.id.text_notifications);//        notificationsViewModel.getText().observe(this, new Observer() {//            @Override//            public void onChanged(@Nullable String s) {//                textView.setText(s);//            }//        });        return root;    }}

在以上的代码中,建立了一个数组 data,演示时为静态数据,实际运行时数据会取自数据库或者 webservice 一类的数据提供接口。

生成实际作用的是三行代码:

ArrayAdapter adapter = new ArrayAdapter&lt;String&gt;(container.getContext(),                android.R.layout.simple_list_item_1, data);        ListView listView = (ListView)root.findViewById(R.id.list_view);        listView.setAdapter(adapter);

1,新建一个 adapter 的适配器,传入的参数是上下文的连接、布局样式文件、数据集,在以上代码中,没有定义布局文件,使用了一个系统内置的文件,可用于显示文本

2,通过 ID 找到文件中的(xml 文件中)的 list_view

3,将两者绑定

三、运行

image-20211122224344305

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值