【发布时间】:2016-05-12 23:46:24
【问题描述】:
我的问题源于做 Android 开发教程,即 Sunshine 应用程序。具体代码是here(一个github pull request diff)。
我在一个布局 XML 文件的 FrameLayout 中有一个 ListView。现在,要将 ListView 与 ViewAdapter(在我的情况下为 ArrayAdapter)一起使用,我需要为适配器和 ListView 将使用的容器(在我的情况下为 TextView)制定布局规范。为什么该容器需要位于单独的布局文件中? (如 github 链接中所示) 我试图将 TextView 放在同一个布局文件中并适当地更改代码,但它只是崩溃(我无法成功调试它): XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView_forecast"
/>
<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"
/>
相关Java代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// create some fake data
String[] arrayList = {
"Today - Sunny - 35/30",
"Tomorrow - Very Sunny - 45/43",
"Today - Dangerous - 55/54",
"Today - Deadly - 62/60",
"Today - Boild an egg? - 100/93",
"Today - Radioactive fallout - 135/130",
"Today - Sunny side up - 150/130",
"Today - Burn - 4000/3978",
};
// pump it into something more managable
ArrayList<String> weatherList = new ArrayList<String>(Arrays.asList(arrayList));
// now create an adapter for the list view so it can feed them to the screen
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weatherList);
// get the list view from the current activity
ListView listView = (ListView) rootView.findViewById(R.id.listView_forecast);
// finally set the adapter
listView.setAdapter(adapter);
return rootView;
}
这个问题以一种不清楚的形式出现 here - 我希望我的措辞正确。
【问题讨论】:
-
因为您正在为适配器动态膨胀/回收视图。视图不是静态添加到主布局中的,它们太动态了。这样想,你的布局是你家的蓝图,你的片段是根据计划建造的房子,而 ListView 的适配器就像车库。你可以在车库里换车,你可以在车库里有不同数量的车,你可以把车拿出来,涂漆,然后放回车库,但你绝不会想要这辆车成为蓝图的一部分。在那里没有任何意义。
标签: java android android-layout listview