代码之家  ›  专栏  ›  技术社区  ›  Anmol

当前使用的布局是横向还是纵向?

  •  1
  • Anmol  · 技术社区  · 5 年前

    我正面临着一个问题,我需要通过使我的视图智能化来解决当前使用的视图类型。

    我有两种布局,一种是纵向的,另一种是横向的。

    • myfragmentlayout.xml
    • myfragmentlayout.xml (土地)

    我正在用一些填充设置片段的子视图,我希望该视图知道当前正在使用的布局类型(纵向/横向)。 这是我使用的代码:

     val verticalPadding = if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
    
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50f, displayMetrics)
    
            else
    
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150f, displayMetrics)
    

    以上的工作是完美的方向改变情况。

    问题:

    我正在为我的应用程序提供多窗口支持,我面临的问题是 窗口 处于纵向模式(即方向为纵向)

    但应用程序由于区域可用而将布局从纵向模式切换到横向模式。

    ScreenShot 如您所见,上面带有红色条的窗口处于纵向模式,但应用程序使用的是它的横向布局(这非常适合我的情况)。

    我想知道如何知道我的应用程序当前使用的布局类型,与移动设备的当前方向无关。

    0 回复  |  直到 5 年前
        1
  •  1
  •   Nicola Gallazzi    5 年前

    我不知道这是否是最好的方法,但是你可以给你的布局不同的容器id,并在onviewcreated方法中搜索这些id。

    例如

    • myfragmentlayout.xml:
    androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/portraitContainer"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
            android:layout_height="match_parent">
    
    • myfragmentlayout.xml(土地)
    <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/landscapeContainer"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
            android:layout_height="match_parent">
    

    然后,在onviewcreated方法中:

    View v = view.findview(R.id.portraitContainer)
    if (v !=null){
      // portrait layout loaded
    } else{
      // landscape layout loaded
    }
    

    如果有帮助,请告诉我;)

        2
  •  0
  •   Anmol    5 年前

    我目前解决这个问题的办法如下。

    我创造了:

    • dimens.xml (/values文件夹)

    • XML (土地) (/values land文件夹)

    存储 Padding Dimension 用于不同类型的布局(纵向和横向)。

    val verticalPadding = context.resources
                                 .getDimension
                                 .getDimension(R.dimens.vertical_padding)
    

    这是我找到的最好的方法。我在寻找一种更好的方法,我可以通过 JAVA/Kotlin 代码和 不是通过单独的xml文件

    在上面的解决方案中,当应用程序选择使用 myfragmentlayout.xml(土地) (横向布局)然后自动应用程序从 迪曼斯(土地)