C/C++プログラマの管理者が, Androidプログラムにチャレンジ. AndroidプログラミングのTipsをメモっていく予定です.

テキストビューやボタンなどの文字色を変更する方法は2通りある.
以下では, テキストビューとボタンの文字色を変更しているが, エディットテキストや他のボタンなど文字列を扱うウィジェットでは同様に文字色を変更できる.



XMLファイルにより設定

  • res/values/colors.xml
    • RGB値かARGB値を用いて, 色情報を定義する.
 color_value:
  #RGB
  #ARGB
  #RRGGBB
  #AARRGGBB
  注) A(α値), R(赤), G(緑), B(青)
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="red">#FF0000</color>
  <color name="lightgreen">#23ce34</color>
</resources>
  • res/layout/main.xml
    • テキストビューに表示する文字列の色を指定する.
    • ボタンに表示する文字列の色を指定する.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView android:id="@+id/textview_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text= "@string/textview_label"
    android:textColor="@color/red"
    />
  <Button android:id="@+id/button_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text= "@string/button_label"
    android:textColor="@color/lightgreen"
    />
</LinearLayout>

コードにより設定

    • テキストビューやボタンなどのsetTextColorメソッドを使って文字色を変える. 引数には色情報をARGB値で指定する.
com.moonlight_aska.android.charcolor01;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.LinearLayout;

public class CharColor01 extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // テキストビューを生成
    TextView text = new TextView(this);
    text.setText(R.string.textview_label);
    text.setTextColor(0xffff0000);
    // ボタンを生成
    Button btn = new Button(this);
    btn.setText(R.string.button_label);
    btn.setTextColor(0xff23ce34);
    // レイアウトにテキストビューとボタンを追加
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(text, new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.WRAP_CONTENT));
    layout.addView(btn, new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.WRAP_CONTENT));

    setContentView(layout);
  }
}



タグ

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu


逆引き(基礎編)

画面表示/操作(49)

フラグメント(1)

逆引き(応用編)

Firebase(2)

AD



管理人/副管理人のみ編集できます