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

ビュー(View)の背景色を変更する方法は2通りある.
以下では, テキストビューとエディットテキストの背景色を変更しているが, 他のビューでも同様に背景色を変更できる.
ただし, エディットテキストやボタンは背景色を設定すると, 本来のエディットテキストやボタンとは異なる表示となってしまうので, 注意が必要.



XMLファイルにより設定

  • 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/text_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#FFFF00"
    android:textColor="#000000"
    android:text="TextView"
    />
  <EditText android:id="@+id/edit01_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#00FF00"
    android:text="EditText"
    />
  <EditText android:id="@+id/edit02_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="EditText"
    />
</LinearLayout>

コードにより設定

  • BackgroundColor01.java
    • View#setBackgroundColorメソッドで, テキストビューに背景色を設定する.
    • View#setBackgroundColorメソッドで, エディットテキストに背景色を設定する.
package com.moonlight_aska.android.backgroundcolor01;

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

public class BackgroundColor01 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.text_label);
    text.setBackgroundColor(0xffffff00);
    text.setTextColor(0xff000000);
    // エディットテキストを生成
    EditText edit01 = new EditText(this);
    edit01.setText(R.string.edit_label);
    edit01.setBackgroundColor(0xff00ff00);
    EditText edit02 = new EditText(this);
    edit02.setText(R.string.edit_label);
    // レイアウトにテキストビューとエディットテキストを追加
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(text, new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.FILL_PARENT,
      LinearLayout.LayoutParams.WRAP_CONTENT));
    layout.addView(edit01, new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.FILL_PARENT,
      LinearLayout.LayoutParams.WRAP_CONTENT));
    layout.addView(edit02, new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.FILL_PARENT,
      LinearLayout.LayoutParams.WRAP_CONTENT));

    setContentView(layout);
  }
}

コメントをかく


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

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

Menu


逆引き(基礎編)

画面表示/操作(49)

フラグメント(1)

逆引き(応用編)

Firebase(2)

AD



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