ListView与ArrayAdapter

本文介绍了Android中ListView与适配器的使用方法。详细解释了如何通过ArrayAdapter将ListView与数据源绑定,并展示了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

适配器是把数据和用户界面关联起来的“粘合剂”。
与其他框架中的类似机制相比,适配器有点特别。适配器本身负责创建 AdapterView 中显示的视图,而 AdapterView 负责指定这些视图的布局方式。例如 ListView 会将视图排成一排,而GridView 会讲视图排成多行多列。
在Android中,ListView是一种很重要的控件 ,一般使用中需建立一个ArrayList,然后通过ArrayAdapter 把ListView绑定到ArrayList上,通过ArrayAdapter来使ListView显示和刷新内容。

添加一个list_item_forecast.xml布局文件

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:id="@+id/list_item_forecast_textview" />

为ListView创建一个ArrayList

String[] data = {
                    "Mon 6/23 - Sunny - 31/17",
                    "Tue 6/24 - Foggy - 21/8",
                    "Wed 6/25 - Cloudy - 22/17",
                    "Thurs 6/26 - Rainy - 18/11",
                    "Fri 6/27 - Foggy - 21/10",
                    "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
                    "Sun 6/29 - Sunny - 20/7"
            };
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));

建立ArrayAdapter并将其与weekForecast绑定的代码如下:

ArrayAdapter<String> mForecastAdapter;

mForecastAdapter = new ArrayAdapter<String>(
                    getActivity(), // The current context (this activity)
                    R.layout.list_item_forecast, // The name of the layout ID
                    R.id.list_item_forecast_textview, // The ID of the textview to populate
                    weekForecast);

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值