2016-06-11 3 views
3

こんにちは、私は開発Androidにかなり新たなんだと私は私自身のカスタムレイアウト作成しようとしています:Androidはカスタムレイアウトに子を追加することはできません(のViewGroupから継承)

public class EqLayout extends ViewGroup { 

public EqLayout(Context context){ 
    super(context); 
} 

public EqLayout(Context context, AttributeSet attrs){ 
    super(context, attrs); 
} 

public EqLayout(Context context, AttributeSet attrs, int defstyle){ 
    super(context, attrs, defstyle); 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    int lato = getLato(); 
    int w = getMeasuredWidth()/lato; 
    int h = getMeasuredHeight()/lato; 
    int ws = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY); 
    int hs = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY); 

    for(int i = 0; i < getChildCount(); i++){ 
     View v = getChildAt(i); 
     v.measure(ws, hs); 
    } 
} 

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    int lato = getLato(); 
    int w = (r - l)/lato; 
    int h = (t - b)/lato; 

    for(int i = 0; i < getChildCount(); i++){ 
     View v = getChildAt(i); 
     int x = i%lato, y = i/lato; 
     v.layout(x*w, y*h, (x+1)*w, (y+1)*h); 
    } 

} 

private int getLato(){ 
    int r = (int) Math.ceil(Math.sqrt(getChildCount())); 
    r = (r > 0) ? r : r+1; 
    return r; 
    } 
    } 

はMainActivity:

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    EqLayout eql = (EqLayout) findViewById(R.id.eqlviewlayout); 
    for(int i = 0; i < 14; i++){ 
     Button b = new Button(this); 
     b.setText("#"+i); 
     eql.addView(b); 
    } 
    } 
} 

、それはXMLです:

XML file

すべてが動作しているようです私は子供をそれに加えることはできません。 私はランタイムとAndroid Studioからボタンをドラッグアンドドロップしてみましたが、成功しませんでした。

誰もがなぜそれが起こるか知っていますか?お時間をありがとう、何か情報が必要かどうか質問してください。

+0

「adb shell dumpsys activity top」の出力は何ですか? – pskink

+0

どうすればその情報を入手できますか? – Levenlol

+0

ターミナルウィンドウで 'adb shell dumpsys activity top'コマンドを実行すると、 – pskink

答えて

1

子供の負の高さです。

ちょうどあなたのonLayoutこの行に置き換えます。

int h = (b - t)/lato; 

int h = (t - b)/lato; 

、あなたは良いです!

Screenshot

関連する問題