简体   繁体   中英

What's alternative to deprecated AbsoluteLayout in Android?

I have a Xamarin project. I develop for IOS,Android and UWP. In my application, I have my manual layout logic for UI Elements. In IOS, I can use the frame property in order to set where the view is going to be rendered. I can do the same in UWP by using Canvas as the container and Canvas.Left,Canvas.Top properties to set x,y locations and my code has the logic to do the layout. I am confused about how to achieve this in Android. AbsoluteLayout seemed to be a perfect match, but it's deprecated. Can I achieve this with some other Layout or should I create my custom ViewGroup class?

You can use a FrameLayout and position items in it using the top and left margin. In XML it would look something like:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="100dp"
    />

</FrameLayout>

If you want to set it from code then you can use the LayoutParams:

FrameLayout.LayoutParams param = (FrameLayout.LayoutParams) view.getLayoutParams();
param.leftMargin = 100;
param.topMargin = 100;
param.height = 50;
param.width = 50;
view.setLayoutParams(param);

Note that the values in code are pixels not dp so you would have to convert. I'm not sure how this would convert to Xaramin but it gives you the idea.

Either way you'll have to consider what will happen when a user with an unusual device size uses your app. The reason Android doesn't have much use for absolute layouts is that there are so many different device sizes/densities that they are usually impractical.

You can use Relative Layout/ Frame Layout / Custom Layout. instead of Absolute Layout, As Absolute layout is harder to maintain is the reason its depreciated.

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