Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

【Android】動的にViewのパラメータを変えたい【layoutParams】

Posted at

【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()
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?