日々精進

新しく学んだことを書き留めていきます

Viewのwidth, heightをコードから変更する

カスタムViewGroupの子Viewのwidth, heightをコードから変更する場合、 setLayoutParamsを使えばいい。ただ、これを実行するタイミングはonMeasure実行以前でないといけない。 例えば、onLayoutはonMeasureの後で呼ばれるのでonLayoutの中でsetLayoutParamsを呼んでも何も起こらない。 兄弟Viewのwidth, heightを使って子Viewのwidth, heightを計算したい場合は兄弟ViewのgetMeasuredWidth等を使えばいい。 例は以下。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) customView.getLayoutParams();
    layoutParams.width = otherView.getMeasuredWidth - 10;
    customView.setLayoutParams(layoutParams);
}

参考: