将视图高度设置为屏幕大小的百分比(以编程方式)

pbl*_*d26 1 java xml layout android android-layout

我正在使用 AndroidSlidingUpPanel 库。 https://github.com/umano/AndroidSlidingUpPanel

我的activity_main.xml 有两个孩子。第一个孩子是主要布局。第二个孩子是上滑面板的布局。在这里,我发布了向上滑动面板的布局。以 15 : 15 : 60 : 10 % 的比例百分比定义了 4 个 LinearLayout。第一个布局将在面板中可见。现在我希望面板高度是第一个布局的 3/4。所以在这里,第一个布局占据屏幕的 15%,但面板高度应该在屏幕的 10-12% 左右。

有什么方法或公式可以用来获取屏幕尺寸并根据此处提供的 xml 文件的第一个布局设置面板高度。

我试图在 Java 代码中定义面板高度。但直到现在还没有成功。有时面板中也会显示第二个布局,有时只有第一个布局的一半或 1/4。

PS:有没有办法在 setContentView() 之前找到视图的高度?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layout_weight="1.5"
    android:background="#666666" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layout_weight="1.5"
    android:background="#888888" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="6"
    android:background="#eeeeee" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#202033" >
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

har*_*ash 7

可以以像素为单位获得屏幕的高度。还可以获取屏幕密度(DPI)。两者的比例将为您提供屏幕的物理高度。

 DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();

      float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
      float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
Run Code Online (Sandbox Code Playgroud)

获得 dpWidth(这是一个与密度无关的物理量)后,您可以轻松地对其应用百分比。