簡體   English   中英

將視圖高度設置為屏幕尺寸的百分比(以編程方式)

[英]Set Height of View as Percentage of screen size(Programmatically)

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

我的activity_main.xml有兩個孩子。 第一個孩子是主要布局。 第二個子項是向上滑動面板的布局。 在這里,我發布了“上滑面板”的布局。 以15:15:60:10%的比例百分比定義了4個LinearLayouts。 第一個布局將在面板中可見。 現在,我希望面板高度為第一個布局的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> 

可以以像素為單位獲取屏幕的高度。 也可以獲取屏幕的密度(DPI)。 兩者的比率將為您提供屏幕的物理高度。

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

      float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
      float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

獲得dpWidth(這是與密度無關的物理量)后,您可以輕松地對其應用百分比。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM