2015-05-17 78 views
0

我的程序有5个“锚点”,我想在onCreate中计算这些点,所以无论屏幕大小如何,它们仍然具有相同的定位点。起初,我试图拉dpi和转换为PX ...将屏幕拆分为三分之二

final float scale = getContext().getResources().getDisplayMetrics().density; 
     int pixels = (int) (dps * scale + 0.5f); 

但这似乎并不适用于我。什么是将屏幕均匀分割成如下几个点的最佳方式:

- - 
- - - 
- - 

回答

0

如何以XML方式执行此操作?

我们只是玩意见的重量。如果您的weightSum为2,那么layout_gravity为1的两个视图将以两半相等的方式分割屏幕。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="30dp" 
     android:orientation="horizontal" 
     android:weightSum="2"> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:text="-" /> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:gravity="center" 
      android:layout_weight="1" 
      android:text="-" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="30dp" 
     android:orientation="horizontal" 
     android:weightSum="3"> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:gravity="center" 
      android:layout_weight="1" 
      android:text="-" /> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:text="-" /> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:gravity="center" 
      android:layout_weight="1" 
      android:text="-" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="30dp" 
     android:orientation="horizontal" 
     android:weightSum="2"> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:text="-" /> 

     <TextView 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:text="-" /> 
    </LinearLayout> 

</LinearLayout> 

有关重量检查thisthis更多信息。

+0

你能解释一下这是如何工作的吗?谢谢 – Nogg

+0

我编辑了我的答案。 –