简体   繁体   English

是否有可能从layout.xml android中的活动中获取变量的值?

[英]Is it possible to obtain the value of a variable from the activity in the layout.xml android?

I need to know if I can obtain a calculated number from my main activity and access it from my layout.xml. 我需要知道我是否可以从主活动中获取计算出的数字,并从我的layout.xml访问它。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int height = displaymetrics.heightPixels;
    int width = displaymetrics.widthPixels;
    float margin_top = (1920f/height) * 125;
    String margin_top_str = Float.toString(margin_top) + "dp";
}

layout.xml code layout.xml代码

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name"
    android:id="button"
    android:background="#f57878"
    android:textSize="48dp"
    android:layout_alignParentTop="true"
    android:layout_marginTop="@MainActivity.java/margin_top_str"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:textColor="#000000" />

The line android:layout_marginTop="@MainActivity.java/margin_top_str" is not real and is only to show what I need. android:layout_marginTop="@MainActivity.java/margin_top_str"不是真实的,只是为了展示我需要的东西。 If what I am asking can be done only in the activity that would work fine too. 如果我要求的只能在可以正常工作的活动中完成。 ps I am a noob. ps我是一个菜鸟。 Thanks 谢谢

No, you can not. 你不能。 You can only reference constants and values from other XML resources but you can't reference java code. 您只能从其他XML资源引用常量和值,但不能引用Java代码。

Instead, calculate the value for different screen sizes and put to corresponding res folders in dimens.xml . 而是,计算不同屏幕大小的值,并将其放入dimens.xml相应的res文件夹。 If it can't be calculated then just set it in runtime through MarginLayoutParams . 如果无法计算,则只需通过MarginLayoutParams在运行时设置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM