首页 > 解决方案 > 将视图的方向设置为其布局的相反方向

问题描述

我有一个基于应用程序语言的相对布局及其方向(有两个方向:LTR 和 RTL),并且我在该布局中有一个视图(CheckBox)。现在我想将 Checkbox 的方向设置为与其布局相反的方向。

有什么建议吗?

编辑

在此处输入图像描述 当布局方向为 LTR 时,我想让此复选框方向为 RTL,当布局方向为 RTL 时,我想让此复选框方向为 LTR。

标签: androidlayoutandroid-layout-direction

解决方案


您可以使用以下代码:

if(config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL)

确定 LayoutDirection 是 RTL 还是 LTR 并以编程方式设置 Checkbox 的位置。

这是一个例子:

布局.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="#00CCCC"
    >
    <RelativeLayout
        android:id="@+id/parentRelativeLayout"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">
        <CheckBox
            android:layout_alignParentRight="true"
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hide...">
        </CheckBox>
    </RelativeLayout>

</RelativeLayout>

MainActivity.java:

package com.example.androidlayout;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    CheckBox checkbox;
    RelativeLayout parent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        parent = (RelativeLayout) findViewById(R.id.parentRelativeLayout);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) checkbox.getLayoutParams();
        Configuration config = getResources().getConfiguration();
        if(config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        }else{
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        }
        checkbox.setLayoutParams(layoutParams);

    }
}

推荐阅读