首先,我做了研究,但找不到任何东西。
我知道这似乎是一个琐碎的问题,但是您究竟如何从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>
在上面的示例中,我想获取“ padding”的值。我该怎么做?这有可能吗?
答案 0 :(得分:0)
您不会“从XML获取值”。相反,您可以从XML中膨胀一个视图,然后可以查询该视图的状态,该状态即为XML声明的状态。
在您的情况下:
首先,您需要为视图提供一个ID,以便您可以在代码中引用它。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/id_for_this_view_here"
android:orientation="horizontal"
android:padding="2dp"
android:layout_width="50dp"
android:layout_height="50dp">
</LinearLayout>
接下来,从XML扩展视图后,可以在“活动”或“片段”中通过该ID找到该视图。例如,如果您处于一个将此布局设置为内容的“活动”中,则可以找到如下视图:
setContentView(R.layout.id_for_the_layout_file);
LinearLayout yourView = findViewById<LinearLayout>(R.id.id_for_this_view_here);
最后,一旦有了视图引用,就可以查询它的状态。例如,在这种情况下,如果您想了解填充,请使用getPaddingLeft()和/或任何其他“ getPadding”方法。
int leftPadding = yourView.getPaddingLeft();
希望有帮助!
答案 1 :(得分:0)
以编程方式获取自己的属性:
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;
//...