android - 将视图的方向设置为其布局的相反方向
问题描述
我有一个基于应用程序语言的相对布局及其方向(有两个方向:LTR 和 RTL),并且我在该布局中有一个视图(CheckBox)。现在我想将 Checkbox 的方向设置为与其布局相反的方向。
有什么建议吗?
编辑
解决方案
您可以使用以下代码:
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);
}
}
推荐阅读
- angular - 带有角度 5 中添加/编辑/删除标题选项的日历组件
- ruby-on-rails - 在跟踪变量 n 的方法中创建循环
- django - Django:基于外键获取多个项目的有效方法
- c# - 如何解决 IronPython 错误
- java - 请求处理失败;嵌套异常是 org.hibernate.MappingException: Unknown entity
- python - Python:获取下一个工作时间段
- c# - Windows 服务不会循环写入日志文件
- dynamic-programming - 斐波那契记忆执行顺序
- sql - 我可以对 Accept 命令使用 IF 语句吗
- java - 通过 java 后端服务器响应本机接收来自 pentaho 数据服务的推送通知