Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】実行時にTextViewのスタイルを動的に変更する方法を解説

このチュートリアルでは、Androidアプリにおいて実行時(ランタイム)にTextViewのスタイルを動的に変更する方法を解説します。画面上のTextViewをタップすると、文字スタイル(太字・斜体)と背景色が切り替わるサンプルを、実際のコードとともに段階的に紹介していきます。

手順1:Android Studioで新規プロジェクトを作成する

Android Studioを開き、メニューから「File」→「New Project」を選択します。必要な設定項目をすべて入力して、新しいプロジェクトを作成しましょう。

手順2:activity_main.xml にレイアウトを記述する

res/layout/activity_main.xml に以下のコードを追加します。画面中央に「Have a nice day!」というテキストを表示するシンプルなTextViewを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Have a nice day!"
        android:textSize="36sp"
        android:layout_centerInParent="true"/>
</RelativeLayout>

手順3:styles.xml にスタイルを定義する

res/values/styles.xml に、切り替え用の2つのスタイルを追加します。「boldText」は太字+斜体+白色、「normalText」は通常スタイル+シルバー色を指定しています。

<resources>
<style name="boldText">
    <item name="android:textStyle">bold|italic</item>
    <item name="android:textColor">#FFFFFF</item>
</style>
<style name="normalText">
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">#C0C0C0</item>
</style>
</resources>

手順4:strings.xml にカラー定義を追加する

res/values/strings.xml に、背景色として使用するカラーリソースを定義します。

<resources>
    <string name="app_name">Sample</string>
    <color name="highlightedTextViewColor">#000088</color>
    <color name="normalTextViewColor">#000044</color>
</resources>

手順5:MainActivity.java にクリック処理を実装する

src/MainActivity.java に以下のコードを追加します。TextViewがタップされたタイミングで setTextAppearance() を呼び出してスタイルを「boldText」へ切り替えるとともに、setBackgroundResource() で背景色を変更しています。

import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < 23) {
                    textView.setTextAppearance(getApplicationContext(), R.style.boldText);
                } else {
                    textView.setTextAppearance(R.style.boldText);
                }
                textView.setBackgroundResource(R.color.highlightedTextViewColor);
            }
        });
    }
}

ポイント:setTextAppearance() はAPIレベル23(Android 6.0)で引数の形式が変わったため、Build.VERSION.SDK_INT でOSバージョンを判定し、適切なメソッドを呼び分けています。

手順6:AndroidManifest.xml を確認する

androidManifest.xml には以下のようにMainActivityを登録します。このサンプルでは特別な権限は不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して動作を確認する

それでは、アプリを実行してみましょう。実機のAndroid端末をPCに接続した状態で、Android Studioのツールバーにある「Run」アイコンをクリックします。デバイスを選択して実行すると、まず初期状態の画面が表示されます。

【Android】実行時にTextViewのスタイルを動的に変更する方法を解説


【Android】実行時にTextViewのスタイルを動的に変更する方法を解説

TextViewをタップすると、テキストが太字・斜体の白文字に変わり、背景色が濃い青色へと変化することが確認できます。このように setTextAppearance() と setBackgroundResource() を組み合わせれば、レイアウトを再読み込みすることなく、実行時に柔軟に見た目を切り替えることが可能です。

  1. Androidのオプションメニューの背景色を変更する方法を徹底解説

    Androidのオプションメニューの背景色を変更する方法この記事では、Androidアプリのオプションメニュー(オプションズメニュー)の背景色を変更する方法を、実際に動作するサンプルコードとともにステップごとに解説します。テーマ(styles.xml)にandroid:itemBackgroundを設定するだけで、メニューの背景色を簡単にカスタマイズできます。ステップ1:新規プロジェクトの作成まず、Android Studioで新しいプロジェクトを作成します。メニューからFile → New Projectを選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。ステップ2:レイアウト

  2. Androidのキーボードを変更する方法を徹底解説!機種別の手順とおすすめアプリもご紹介

    Android OSの大きな魅力のひとつは、自由度の高いカスタマイズ性です。その代表格ともいえるのが、スマートフォンの初期搭載(ストック)キーボードを好みのものへ変更できる機能です。この変更は、Samsung、Google、Huawei、Xiaomiなど、端末のブランドを問わず行うことができます。多くの純正キーボードは十分に優秀ですが、ユーザーのニーズによっては別のキーボードが必要になることもあります。例えば、他の言語で入力したい場合や、数式で数学記号を使いたい場合など、標準キーボードが対応していない機能が必要なケースです。Androidキーボードの変更手順は基本的にどの端末でも共通しています