【问题标题】:How can I access screen width and height of Android mobile in the shared code?如何在共享代码中访问 Android 手机的屏幕宽度和高度?
【发布时间】:2017-07-25 23:05:23
【问题描述】:

如何在共享代码中访问 Xamarin.Android 设备的屏幕宽度和高度?我无法使用资源。它在给定的上下文中找不到资源。

为了清楚起见,我想为不同的方向(纵向和横向)展示不同的 uı 设计。因此,我想在共享代码中达到平板电脑/手机的方向。

这是我的第一个问题,询问是否有办法检查它是横向还是纵向: A way to check if it is in the landscape or portrait mode in Xamarin.Android

我认为共享代码中 Android 手机的屏幕宽度和高度会对我有所帮助。

【问题讨论】:

    标签: xamarin xamarin.android


    【解决方案1】:

    实际上有一个很好的关于在 xamarin.android 中检测屏幕尺寸的小指南,可以在 xamarin developer guide website 上找到。

    在 onCreat 方法的 'Activity.cs' 中,只需添加以下内容:

    public static Rotation screenOrientation;
    
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
    
        var metrics = Resources.DisplayMetrics;
        var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
        var heightInDp = ConvertPixelsToDp(metrics.HeightPixels);
    
        if(widthInDp > heightInDp)
        {
            screenOrientation = Rotation.Landscape;
        }
        else
        {
            screenOrientation = Rotation.Portrait;
        }
    }
    

    如果您想轻松区分横向和纵向,我会在某处使用一点枚举。

    public enum Rotation
    {
        Landscape,
        Portrait
    }
    

    我认为这样的事情可以解决问题。

    【讨论】:

    • 我无法使用,因为我没有使用 Xamarin.Forms。我正在使用 Xamarin.Android。
    • @KaanEKİN 因为您在 OP 中包含了 xamarin.forms 标记,所以您已经获得了三个基于表单的答案,您需要更加小心,我已经提交了编辑。
    • 抱歉,新来的
    • @KaanEKİN 没关系,伙计,当我有机会时,我会编辑我的答案以与 android 相关。
    • 非常感谢
    【解决方案2】:

    onConfigurationChanged 将帮助您检测设备是横向还是纵向。关注this

    如果你真的想获得屏幕宽度或高度。试试这个

    /**
     * @param activity Context
     * @return a integer value represent the width of physical device
     */
    public static int getScreenHeight(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return metrics.heightPixels;
    }
    
    /**
     * @param activity Context
     * @return a integer value represent the width of physical device
     */
    public static int getScreenWidth(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return metrics.widthPixels;
    }
    

    【讨论】:

    • 我把这些代码放到MainActivity.cs中。现在我该怎么称呼他们?
    【解决方案3】:

    以下代码将帮助根据手机屏幕的高度和宽度设计手机屏幕。

    基于此的设计将适合所有移动分辨率。

    PCL:

    App.cs

    public class App : Application
    {                     
      public static int screenHeight, screenWidth;
    
     public App()
      {           
        MainPage = new UserLogin();
        //The root page of your application         
       }
    
       protected override void OnStart()
       {
         // Handle when your app starts
       }
    
    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }
    
    protected override void OnResume()
    {
        // Handle when your app resumes
       }
     }
    

    Xamarin.Android:

    MainActivity.cs

    #region 屏幕高度和宽度

        var pixels = Resources.DisplayMetrics.WidthPixels;
        var scale = Resources.DisplayMetrics.Density;
    
        var dps = (double)((pixels - 0.5f) / scale);
    
        var ScreenWidth = (int)dps;
    
        App.screenWidth = ScreenWidth;
    
        //RequestedOrientation = ScreenOrientation.Portrait;
    
        pixels = Resources.DisplayMetrics.HeightPixels;
        dps = (double)((pixels - 0.5f) / scale);
    
        var ScreenHeight = (int)dps;
        App.screenHeight = ScreenHeight;
    

    结束区域

    Xamarin.iOS

    AppDelegate.cs

    #region For Screen Height & Width
    
      App.screenWidth = (int)UIScreen.MainScreen.Bounds.Width;
          App.screenHeight = (int)UIScreen.MainScreen.Bounds.Height;
    

    #endregion

    PCL:

    如果您使用 MVVM 模式,您必须在 ViewModel 中获取这些 ScreenHeight 和 ScreenWidth 然后为您的视图和布局提供高度和宽度。

             // The below two lines will use to get the MOBILE SCREEN HEIGHT && WIDTH in ViewModel
              int heightScreen=App.screenHeight;
              int widthScreen=App.screenHeigh;
    

    XAML 设计:

    UserLogin.xaml

       <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:local="clr-
      SreenSizeDemo;assembly=SreenSizeDemo" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
       x:Class="SreenSizeDemo.UserLogin">
      <StackLayout>
       <Label x:Name="lblTitle" HorizontalOptions="FillAndExpand"/>
       <Image x:Name="imgProfile"  Source="Logo.png" />
      <StackLayout>
      <ContentPage>
    

    UserLogin.xaml.cs

      public partial class UserLogin : BaseContentPage
      {
              // Here you get the MOBILE SCREEN HEIGHT && WIDTH
              int heightScreen=App.screenHeight;
              int widthScreen=App.screenHeight;
    
     public UserLogin()
         {
                           lblTitle.FontSize=height=Screen/36.8;
                         //The above value is equal to fontsize =20
                         imgProfile.HeightRequest=heightScreeen/10;
                         imgProfile. WidthRequest=heightScreeen/10;
                }
          }
    

    C# 设计:

     public class UserLogin: ContentPage
          {
              // Here you get the MOBILE SCREEN HEIGHT && WIDTH
              int heightScreen=App.screenHeight;
              int widthScreen=App.screenHeight;
    
              public UserLogin()
                   {
                       Label lab = new Label()
                        {
                          FontSize = heightScreen/ 36.8
                          //the above value is equal to fontsize =20
                        };
    
                       Image imgProfile=new Image()
                        {
                             Source="Logo.png",
                             HeightRequest=heightScreeen/10,
                             WidthRequest=heightScreeen/10
                      }
              }
         }
    

    【讨论】:

      【解决方案4】:

      您似乎正在尝试设置某些控件相对于屏幕尺寸的高度和宽度。如果您使用的是 Xamarin Forms,则可以使用 Grid 实现比例尺寸。使用 Xamarin Forms 的整个想法是您不必担心外形尺寸。

      因此,在您的 Xaml 中,您可以通过以下方式使用 Grid

       <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:local="clr-SreenSizeDemo;assembly=SreenSizeDemo" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SreenSizeDemo.UserLogin">
        <Grid x:Name="ContentGrid">
          <Grid.RowDefinitions>
              <!--This row will resize depending upon the size of the content within it-->
              <RowDefinition Height="Auto">
              <!--This will take 10% of  your total screen height-->
              <RowDefinition Height="0.1*">
              <!--This will take rest of the available the screen height (i.e. ScreenHeight - Row0Height - Row1Height)-->
              <RowDefinition Height="*">
          </Grid.RowDefinitions>
              <Label x:Name="lblTitle" Grid.Row="0" HorizontalOptions="FillAndExpand"/>
              <!--You don't need to set both height and width of the image, setting either of them is enough. Unless your ImageAscpect property neither of these AspectFill, AspectFit values-->
              <Image x:Name="ImgProfile" Grid.Row="1" Source="Logo.png"/>
              <!--Rest of your contents go in third row-->
          </Grid>
        <ContentPage>
      

      您可能需要在后面的代码中做的唯一事情是为标签控件设置FontSize。在这种情况下,您可以设置相对于高度的字体大小,而不是使用屏幕大小网格。

      public UserLogin()
      {
        lblTitle.FontSize = ContentGrid.Height/10;
      }
      

      另外,如果获取屏幕尺寸是不可避免的,我建议您使用依赖服务来获取屏幕尺寸,而不是使用全局静态属性

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-22
        • 2011-06-12
        • 2012-11-01
        • 1970-01-01
        • 2018-02-02
        • 1970-01-01
        • 2011-09-25
        相关资源
        最近更新 更多