2015-10-12 30 views
0

我想在絕對佈局的屏幕中間放置一個視圖。無法使用絕對佈局準確地在屏幕中間定位視圖

首先,我得到了屏幕高度以像素爲單位

Display display = getWindowManager().getDefaultDisplay(); 
    Point size = new Point(); 
    display.getSize(size); 
    int height_px = size.y; 

其次,我轉換了屏幕高度爲密度像素

Resources resources = this.getResources(); 
    DisplayMetrics metrics = resources.getDisplayMetrics(); 
    float height_dp = height_px/(metrics.densityDpi/160f); 

然後,我打印出密度屏幕高度的價值測試像素

Log.v("TAG height: ", String.valueOf(height_dp)); // prints 640  

最後,我設置了第二個視圖的y偏移量purple_view到640(320)的一半。

<AbsoluteLayout 
    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:paddingLeft="0dp" 
    android:paddingRight="0dp" 
    android:paddingTop="0dp" 
    android:paddingBottom="0dp" 
    tools:context=".MainActivity"> 

    <View 
     android:id="@+id/white_view" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#FFFFF0" 
     android:layout_y="0dp" 
     /> 

    <View 
     android:id="@+id/purple_view" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#FF0FF0" 
     android:layout_y="320dp" 
     /> 

</AbsoluteLayout> 

然而,purple_view視圖是不完全在屏幕中間的位置。

enter image description here

+2

@ the_prole:'AbsoluteLayout'已棄用one ..請使用其他佈局.. !! – AndiGeeky

+0

@AndiGeeky這是我知道的在屏幕外定位視圖的唯一方式。 –

+0

你在屏幕外*是什麼意思?你爲什麼不簡單地使用中心重力? –

回答

0

使用此可能會有所幫助:

ImageView iv = new ImageView(this); 
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(30, 40); 
params.leftMargin = 50; 
params.topMargin = 60; 

rl.addView(iv, params); 

改變數值爲u需要。

+0

解決方案是添加狀態和操作欄的高度的一半 –