Androidアプリで動的に追加したViewにスタイルを適用する方法【Java】

動的に追加したViewにスタイルを適用する方法

概要

動的に追加したViewのスタイルを変更する場合、setBackgroundColor、setTextColor、setPaddingなどのメソッドがありますが、xmlファイルからスタイルを適用したい場合は少し変わった方法が必要です。

ContextThemeWrapperを使って、Viewを生成するときのコンストラクターに引数として渡します。

スタイルを作成する

res/values/themes.xmlにsampleStyleというスタイルを作成しました。


<resources xmlns:tools="http://schemas.android.com/tools">
    <style name="sampleStyle">
        <item name="android:textSize">16sp</item>
        <item name="android:padding">20dp</item>
        <item name="android:background">@color/black</item>
        <item name="android:textColor">@color/white</item>
    </style>
</resources>

レイアウトファイルを作成する

レイアウトファイルは以下のようになっています。空のLinearLayoutがあるだけです。


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/linearLayout"
    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"
    android:orientation="vertical"
    tools:context=".MainActivity">
</LinearLayout>

Viewを作成して追加する

Javaコード側では以下のようになります。


import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout linearLayout = findViewById(R.id.linearLayout);

        TextView textView = new TextView(new ContextThemeWrapper(this, R.style.sampleStyle));
        
        textView.setText("こんにちは。");
        
        linearLayout.addView(textView);
    }
}

TextViewをインスタンス化する際、通常はコンテキスト(this)を渡しますが、スタイルを指定する場合はContextThemeWrapperを渡します。

ContextThemeWrapperの引数は(コンテキスト, スタイルのリソースID)です。

作成したTextViewをLinearLayoutのaddView()メソッドで追加します。これで動的に追加したViewにスタイルを適用できます。

Androidで動的に作成したViewにスタイルを適用する方法

投稿されたコメント一覧

コメント投稿フォーム

必須項目
任意項目

ウェブサービス一覧