2017-01-12 17 views
0

我有一個自動生成一些框架佈局的自定義相對佈局。每個框架佈局都有一個Height和Margin-Top,取決於我的CustomView的高度。如果我試圖從構造函數中獲得,我收到null作爲答案。我嘗試過getHeight()getMeasuredHeight(),但它不起作用。我可以覆蓋onMeasure()onLayout()方法,但我不能使用我得到的值,因爲這2個方法在構造函數之後被調用。在xml構造函數中獲取CustomView的高度

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

<com.cviing.cviing.FolderStackLayout 

    android:background="@color/colorAccent" 
    android:id="@+id/activity_cv2" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.cviing.cviing.CV2" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools"> 


</com.cviing.cviing.FolderStackLayout> 

類:

public class FolderStackLayout extends RelativeLayout { 
    int gap = 10; 
    int foldersNumber = 10; 
    Context context; 
    int height; 
    private int position; 
    int baseTop; 


public FolderStackLayout(Context context) { 
    super(context); 
    init(context, null, 0); 
} 

public FolderStackLayout(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    init(context, attrs, 0); 

} 

public FolderStackLayout(Context context, AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 
    init(context, attrs, defStyleAttr); 

} 


public void init (Context context, AttributeSet attrs, int defStyleAttr){ 
    this.context = context; 
    createView(); 

} 

@Override 
protected void onLayout(boolean changed, 
         int left, 
         int top, 
         int right, 
         int bottom) { 
    int height = getMeasuredHeight(); 
    if (height > 0) { 
     baseTop = height/getCount() - gap; 
    } 
} 

public int getCount(){ 
    return foldersNumber; 
} 



public int getPosition() { 
    return position; 
} 
public void createView(){ 
} 
} 

我該怎麼辦?

回答

0

在構建View時,高度未知。例如,假設我有:

void foo() { 
    new FolderStackLayout(); 
} 

很明顯,那FolderStackLayout不會有高度。這是一個Java對象,僅此而已。小部件和容器只能在添加到某個父級後才進行測量和佈局,並且在構造函數返回後很長時間。

無論你在做什麼工作都需要轉移到別處,例如你提到的onMeasure()onLayout()

+0

我不創建一個對象。我已經在xml文件中創建了它,並且指定了他的高度是MATCH_PARENT。 –

+0

@FabioPiunti:沒關係。 – CommonsWare

+0

我無法從onMeasure()添加孩子。 onLayout()或onDraw()。這常見問題經常被調用,並不方便 –

相關問題