Viewを表示する
Viewを表示する
レイアウトファイルに要素を追加する。
Activity
やFragment
の画面表示処理でレイアウトファイルを各画面に当てこむが、
そのレイアウトファイルに表示したいView
を追加する。
例えばAndroidStudioでシンプルなプロジェクトを新規作成するとactivity_main.xml
が生成されるので確認する。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
FrameLayout
は複数のViewを配置する場合に使用する ViewGroup
クラス派生のクラスのひとつ(説明は割愛)。
その中にTextView
というテキストを表示するためのView
が配置されている。
↑のファイルをActivity.setContentView(resId)
でリソースIDとして渡すことで、
Activity
で表示する画面レイアウトとして当てこむ。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
// Activityで表示する画面として↑のレイアウトファイルを指定
setContentView(R.layout.activity_main)
...
}
Viewの大きさを設定する
レイアウトファイルにView
を配置する際、必須項目としてandroid:layout_width
とandroid:layout_height
がある。
この設定項目でView
の大きさを指定することができる。
Viewの幅を設定する
android:layout_width="wrap_content"
のwrap_content
を大きさ指定に変更する。
- 数値を指定する場合、単位として
dp
を使う。例えば100
を指定する場合はandroid:layout_width="100dp"
となる。
Viewの高さを設定する
android:layout_height="wrap_content"
のwrap_content
を大きさ指定に変更する。
- 数値を指定する場合、単位として
dp
を使う。例えば100
を指定する場合はandroid:layout_height="100dp"
となる。
最終更新: 2025.6.24