【Kotlin/Android Studio】Includeタグの使い方!ビューを再利用する方法

この記事からわかること

  • Android Studio/kotlinIncludeタグ使用方法
  • ビュー再利用するには?
  • HeaderContentsFooterなどを使い回す方法

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

Includeタグでビューを再利用する方法

Android StudioでHeaderやContents、Footer部分などを定義し再利用するにはincludeタグを使用します。使い方は簡単で再利用したいビューを用意しincludeタグから指定するだけです。


<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: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="activity_main.xml"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="34sp" />

    <include layout="@layout/fragment_contents"
        android:id="@+id/include_contents" />

</androidx.constraintlayout.widget.ConstraintLayout>

layout属性に読み込みたいFragmentを指定し、識別用のidも付与しておきます。Fragment側は特に何も変わらずに準備しておきます。


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ContentsFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Include Fragment View"
        android:textAlignment="center"
        android:textSize="34sp" />

</FrameLayout>
【Kotlin/Android Studio】Includeタグの使い方!ビューを再利用する方法

MainActivityから参照する

MainActivity.ktからincludeされている中のTextViewなどを参照するにはfindViewByIdメソッドを2回呼び出せばOKです。

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val mainText:TextView= findViewById(R.id.text_view)

        mainText.text = "これはメインアクティビティのテキストです"

        val includeText:TextView= findViewById<FrameLayout>(R.id.include_contents).findViewById(R.id.include_text_view)
        includeText.text = "これはインクルードされたテキストです"

    }
}

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index