2017-01-12 7 views
0

私は、カスタムレイアウトを自動的に生成するカスタムレイアウトを持っています。各フレームレイアウトの高さと余白は、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()。このmhetodsは頻繁に呼び出され、それは便利ではない –

関連する問題