Share via

Determine Layout Based On Screen Width

Nathan Sokalski 4,111 Reputation points
2021-04-02T22:15:11.607+00:00

I have a component of my app for which I want a different layout depending on the width of the screen. I do not need to use a different layout for the entire app, only for one small part of the main layout. The component that will be different depending on the screen width is a GridLayout. I have looked at the following:
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/resources-in-android/resources-for-varying-screens?tabs=windows
But that seems like it wants separate folders and is intended for designs that are completely different for different sizes. I have only one component that will be different. Is there some way to use something like a selector to do this? The stuff in the link above seems like a lot of work for just one small adjustment. Is there any way to simply say something like "Use Layout A if the screen is wider than x, otherwise use Layout B"? Thanks.

Developer technologies | .NET | Xamarin
0 comments No comments

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,971 Reputation points
    2021-04-05T08:59:42.08+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Is there any way to simply say something like "Use Layout A if the screen is wider than x, otherwise use Layout B"?

    Try to get the parent layout of the dynamic view in the OnCreate method, then detect the device's width to add the view.

       <LinearLayout  
               android:id="@+id/testLayout"  
               android:orientation="vertical"  
               android:layout_width="match_parent"  
               android:layout_height="wrap_content"/>  
         
       //add the view according to the device's size in the OnCreate method  
       var testLayout = FindViewById<LinearLayout>(Resource.Id.testLayout);  
         
       if (xxx)  
       {  
           testLayout.AddView(text);  
       }  
       else  
       {  
           testLayout.AddView(_button);  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.