首页 > 解决方案 > 如何以编程方式从 XML 中获取值?- 安卓

问题描述

首先,我确实做了我的研究,但找不到任何东西。

我知道这似乎是一个微不足道的问题,但是您究竟如何从 XML 文件中检索值(在我的例子中,是布局 XML)

这是我的代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="2dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

</LinearLayout>

在上面的例子中,我想得到“填充”的值。我该怎么做?这甚至可能吗?

标签: androidxml

解决方案


以编程方式获取自己的属性:

LinearLayout linearLayout = findViewById(R.id.your_layout_id);
int p = linearLayout.getPaddingTop();
int b = linearLayout.getGravity();
//...

获取其与其布局容器的相对位置:

例如,您的线性布局位于 ConstrainLayout 中:

ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) linearLayout.getLayoutParams();
int t = layoutParams.topMargin;
int b = layoutParams.leftMargin;
//...

推荐阅读