ASとか

開発系の記事が多めです。タイトルのASはActionScriptの略です。

ImageViewへのLayoutParams設定でハマった

はじめに

ActivityのonWindowFocusChanged()で動的にImageViewのサイズを変更したかったのだが、ClassCastExceptionがしつこかったのでメモ

エラーが出る書き方

layout
<FrameLayout
        android:id="@+id/contents_base"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
    >
    <ImageView
        android:layout_height="wrap_content"
        android:id="@+id/contents_image"
        android:layout_width="fill_parent"
        android:layout_gravity="bottom"
        android:scaleType="fitXY"/>
</FrameLayout>
onWindowFocusChanged()
imageview.setLayoutParams(new ViewGroup.LayoutParams(Width, Height));

ドキュメントの通りViewGroup.LayoutParamsを渡しているつもりなんだけどなー

正解

最初記事を見た瞬間にLinearLayout.LayoutParamsを使えばいいんだ!と思いClassCastExceptionと再会したのですが、読んだ感じだと"LinearLayoutの内側にあれば"とあるので、僕の場合はFrameLayoutじゃないですかと思い

imageview.setLayoutParams(new FrameLayout.LayoutParams(Width, Height));

と書いたらいけた。ちなみにWidthとかの部分はViewGroup.LayoutParams.FILL_PARENTとかでも大丈夫です。

おまけ

layout見たらわかる通りlayout_gravity="bottom"を設定してるんだけどFrameLayout.LayoutParamsを設定したらこれが初期化された。なので

imageview.setLayoutParams(new FrameLayout.LayoutParams(Width, Height, Gravity.BOTTOM));

とやって終了。なぜ初期化されるのかは正確にはわからないけどFrameLayoutの性質を考えるとそんな不思議でもないような気がする