【Android】動的にViewのパラメータを変えたい【layoutParams】
layoutParamsとは?
Viewが所属する親のレイアウトによって提供されるパラメータで、
Viewがどのようにレイアウトされるかを動的に指定できます。
動的に変化する代表的なものを紹介します。
①幅と高さの指定
Viewの幅や高さを指定したいときは、layoutParams.widthおよびlayoutParams.heightプロパティを
sampleView.layoutParams.width = 500 // 幅を500ピクセルに設定
sampleView.layoutParams.height =100 //高さを100dpに設定
sampleView.layoutParams.width =ViewGroup.LayoutParams.WRAP_CONTENT //幅をwrap_contentに設定
sampleView.layoutParams.height =ViewGroup.LayoutParams.MATCH_PARENT //高さをmatch_parentに設定
//
sampleView.requestLayout() // 変更を反映させる。
②マージンの指定
// 例: マージンを設定するView
val yourView = binding.yourView
// マージンを設定
val layoutParams = yourView.layoutParams as ViewGroup.MarginLayoutParams
layoutParams.leftMargin = 16 // 左側のマージン
layoutParams.topMargin = 8 // 上側のマージン
layoutParams.rightMargin = 16 // 右側のマージン
layoutParams.bottomMargin = 8 // 下側のマージン
// レイアウトの再計算を要求
yourView.requestLayout()