AndroidでArrayAdapterやSimpleAdapterを使ってListViewにデータを表示するとき、テキストの内容によってTextViewの背景色を変えたいと思いました。
やり方はいろいろあるんでしょうが、簡単な方法を考えました。
TextViewを継承して独自のTextViewを作る
背景色を変えたいTextView用に独自のTextViewクラスを作成します。
AppCompatTextViewを継承して作成します。
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
public class StateTextView extends AppCompatTextView {
public StateTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
if (text.toString().indexOf("未処理") != -1) {
setBackgroundColor(Color.RED);
setTextColor(Color.WHITE);
setBackgroundResource(R.drawable.choice1_text);
} else if (text.toString().indexOf("当選") != -1) {
setBackgroundColor(Color.YELLOW);
setTextColor(Color.WHITE);
setBackgroundResource(R.drawable.choice5_text);
} else {
setTextColor(Color.BLACK);
setBackgroundColor(Color.argb(0, 0, 0, 0));
}
}
}
テキスト変更時のイベントで背景色を設定してあげればOKです。
ListViewに表示する列のxmlは以下。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="40sp"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/name"
android:layout_width="250sp"
android:layout_height="wrap_content"
android:layout_margin="5sp"
android:focusable="false"
android:focusableInTouchMode="false"
android:textColor="@android:color/black" />
<StateTextView
android:id="@+id/stateString"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5sp"
android:layout_weight="1"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center"
android:padding="5sp"
android:textColor="@android:color/black" />
</LinearLayout>
スポンサーサイト
アフィリエイトはエーハチネット
ドメイン取るならお名前.com
