我正在构建一个 android 应用程序并且我有一个对话框 fragment 。对话框 fragment 具有设定的宽度。但是,问题是当应用程序在屏幕尺寸不同的设备上运行时,对话框 fragment 未正确居中。
最初,我拥有的是:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="500dp"
android:layout_height="wrap_content">
<-- code goes here -->
</RelativeLayout>
如您所见,我有一个具有已定义宽度的 relativeLayout。因为我知道你不能在相对布局中使用 layout_weight
,所以我所做的是将父相对布局包装在线性布局中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:weightSum="1">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</RelativeLayout>
</LinearLayout>
但是,这不起作用,因为当我在屏幕尺寸较小的设备上运行应用程序时对话框 fragment 被剪切。
如何将对话框 fragment 的宽度设置为屏幕尺寸的百分比?这完全可能吗,还是我必须求助于以编程方式设置它?
最佳答案
这是一个正确的方法,如果你想让 RelativeLayout 有 40% 的屏幕宽度,但是这个技术不能应用于父布局,因为父布局没有父布局,android:layout_weight 不影响
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="100">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="40">
</RelativeLayout>
Since I know that you can't use layout_weight in a relative layout
我们可以在任何 View 和布局中使用 layout_weight,如果它是 LinearLayout 的直接子级
关于android - 将父线性布局的宽度设置为屏幕的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28718069/