根据显示方向更改XML填充属性



在我的XML布局中,我试图根据显示方向在LinearLayout上设置不同的paddingTop。

上面的代码是用于纵向模式的,但在横向模式下,我想要,例如android:paddingTop="20dp"

<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingStart="5dp"
android:paddingEnd="0dp"
android:paddingTop="60dp"
android:orientation="vertical">
<TextView></TextView>
<TextView></TextView>
</LinearLayout>

它可能来自XML,还是需要我在屏幕方向更改时以编程方式管理它?

谢谢。

使用xml执行此操作时有两个选项。为纵向/横向指定不同的布局文件,或者使用单个布局文件并定义纵向/横向的不同尺寸。

不同布局文件

只有在纵向/横向布局明显不同的情况下,才有必要使用不同的布局。随着应用程序大小的增长,维护不同的布局变得更加困难。在res文件夹中,您需要创建两个子文件夹:

res/layout-port
res/layout-land

然后,您将在每个文件夹中创建一个具有相同名称的文件。当设备处于纵向时,使用layout-port中的文件,而当设备处于横向时,则使用layout-land中的文件。

不同的Dimens文件

第二种选择是使用一个布局文件,但在其中定义一个动态维度。首先,您需要在res文件夹中创建两个文件夹:

res/values-port
res/values-land

然后,您需要在每个文件夹中创建一个名为dimens.xml的文件。在values-port文件夹中,您可以将其设置为:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="main_screen_padding_top">60dp</dimen>
</resources>

values-land文件夹中,您可以将其设置为:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="main_screen_padding_top">20dp</dimen>
</resources>

然后在布局xml文件中,您可以引用该dimen值:

<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingStart="5dp"
android:paddingEnd="0dp"
android:paddingTop="@dimen/main_screen_padding_top"
android:orientation="vertical">
<TextView></TextView>
<TextView></TextView>
</LinearLayout>

它将根据设备的方向使用适当的尺寸。

出于您的目的,我建议使用二聚体方法,因为它通常更容易维护。

最新更新