简体   繁体   中英

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.

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

<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. If what I am asking can be done only in the activity that would work fine too. ps I am a noob. Thanks

No, you can not. You can only reference constants and values from other XML resources but you can't reference java code.

Instead, calculate the value for different screen sizes and put to corresponding res folders in dimens.xml . If it can't be calculated then just set it in runtime through MarginLayoutParams .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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