适配器是把数据和用户界面关联起来的“粘合剂”。
与其他框架中的类似机制相比,适配器有点特别。适配器本身负责创建 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);