gpt4 book ai didi

java - 为什么 ListView 需要将其容器项放在单独的布局文件中

转载 作者:行者123 更新时间:2023-12-01 09:56:12 26 4
gpt4 key购买 nike

我的问题源于做 Android 开发教程,即 Sunshine 应用程序。具体代码为here (github 拉取请求差异)。

我在一个布局 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 - 我希望我的措辞正确。

最佳答案

布局中的 TextView 不是 ListView 的子级,它是同级。 ListView 根据适配器报告的项目数量、每个子项(行)有多大以及屏幕上有多少空间来显示它们来管理其子项。

无论您对该行使用什么 View ,每一行都需要该 View 自己的实例。将 View 放置在布局中将导致创建一个实例并将其添加到 View 层次结构中,但是ListView可以拥有任意数量的子级,具体取决于您的数据中的数据适配器。如果您的适配器有 3 个项目,并且每行只是一个 TextView,那么您需要 3 个 TexView 来显示所有项目,而不仅仅是您添加的项目。

这就是为什么将行布局包含在与 ListView 相同的布局中的任何位置是没有意义的。

关于java - 为什么 ListView 需要将其容器项放在单独的布局文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191264/

26 4 0