2014-09-01 80 views
0

我正在嘗試使用layout_marginLeftlayout_marginTop設置自定義視圖的x和y座標。當一個佈局膨脹,我試圖實例化過程中獲得的佈局參數,像這樣:從視圖獲取佈局邊距

public class Stick extends View { 

    int x, y; 

    public Stick(Context context) { 
     RelativeLayout.LayoutParams layout = (RelativeLayout.LayoutParams) getLayoutParams() 
     x = layout.leftMargin; 
     y = layout.top_Margin; 
    } 
} 

編輯:忘了XML:

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 
<com.test.app.Stick 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_marginLeft="30dp" 
     android:layout_marginTop="30dp"/> 
<com.test.app.Stick 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="20dp" 
     android:layout_marginTop="20dp" 
     android:layout_centerInParent="true"/> 
</RelativeLayout> 

這將導致應用沒有任何錯誤立即崩潰雖然。難道我做錯了什麼?

回答

0

在您的代碼中試試這個。

RelativeLayout.LayoutParams layout = (RelativeLayout.LayoutParams) yourLayout.getLayoutParams(); 
     x = layout.leftMargin; 
     y = layout.topMargin; 

這裏yourLayout是你想要獲得邊距的佈局。

+0

我得到一個NullPointerException。是否因爲我試圖從視圖構造函數中獲取佈局參數? – Raggeth 2014-09-01 21:52:32

+0

請參閱已編輯的答案。您應該使用'someLayout.getLayoutParams()'。 – 2014-09-01 22:10:27