gpt4 book ai didi

java - 元素没有到达 fragment XML 中应有的位置

转载 作者:行者123 更新时间:2023-12-02 13:13:04 25 4
gpt4 key购买 nike

fragment_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/movies_fragment_ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MoviesFragment">

<ListView
android:id="@+id/lvMovies"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#efefef"
android:layout_weight="100"/>

<Button
android:id="@+id/bLoadData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load api data"
android:layout_weight="1"/>

</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">

<include layout="@layout/fragment_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

</LinearLayout>

来自 MainActivity.java 的 onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.movies_fragment_ll, new MoviesFragment())
.commit();
}
}

enter image description here

从屏幕截图中可以看到,代码的目的是显示左侧的内容,但实际显示的内容是不同的。我尝试使用 XML 和 java,但它一直这样做。在某些情况下,根据我在屏幕上排列 ListView 和 Button 的方式,我有时会得到两个 Button,而不是一个。

为什么?

为了消除困惑。数据正在添加到 ListView。单击按钮即可添加数据。

但在单击按钮之前,数据已添加到 ListView。

如何使 ListView 高度恰好位于按钮从底部开始的位置。使布局看起来像 XML 预览中的布局。

最佳答案

Android 预览显示一个带有子项的列表。但是在运行时,您没有在 ListView 中添加任何元素,因此 ListView 为空。在这种情况下,您的按钮会向上移动。

如果您希望按钮固定在底部,请使用相对布局。

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/movies_fragment_ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MoviesFragment">


<Button
android:id="@+id/bLoadData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load api data"
/>
<ListView
android:id="@+id/lvMovies"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#efefef"
android:layout_above="@id/bLoadData"
android:layout_weight="100"/>

</RelativeLayout>

关于java - 元素没有到达 fragment XML 中应有的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com