俺言語。

自分にしか理解できない言語で書かれた備忘録

【Android, Spinner】Spinnerの文字色を動的に変化させる方法

スピナーで選択した文字が条件に一致したときに通常の白から緑に変化させて,選択した文字のstatusを明示できるようにしたもの.

流れは,

  1. SpinnerにセットするArrayAdapterを自作する.
  2. 自作ArrayAdapterにテキストカラーを保持するメンバを追加
  3. getView()の中でTextViewの文字色をメンバの色で更新し,そのTextViewを戻り値にする
  4. 自作メソッドを追加し,テキストカラーを外部から変更できるようにする.
  5. テキストカラーを操作したとはアダプタークラスに変更通知(customAdapter.notifyDataSetChanged();)を送り,画面を更新する

ポイントは,

  • 表示される色だけを操作する場合はgetView()の内部を変更する.プルダウンで表示されるリストの色はgetDropDownView()の方でやれるはず.
  • DropDownリストを変えなくてもoverrideする必要あり.その際に,LayoutInflater.from(getContext()).inflate(R.layout._spinner_item, parent, false); としてあげないとプルダウンでタップできるエリアが狭くなってしまい,選択しづらくなる.
  • getDropDownView()内で,表示するテキストとテキストカラーも明示が必要.
/***
* スピナーの文字色を動的に返るための自作ArrayAdapterクラス
*/
public class CustomAdapter extends ArrayAdapter<String>{

    int textcolor = Color.WHITE;
    String textString =  new String(" ");

    // Constructor
    public CustomAdapter( Context context, int resource, String[] strings){
    super(context, resource, strings);
    }

    @NonNull
    @Override
    // スピナーに表示されるビューのみ色を変えられる様に変更する
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        TextView textView
                    = (TextView)((LayoutInflater.from(getContext()).inflate(
                    R.layout._spinner_item, parent, false)));

        textString = super.getItem(position); // Spinnerを選択したときのテキストの変更も外でやる必要あり
        textView.setText(textString);

        // スピナーに表示されるテキストの色変更
        textView.setTextColor(textcolor);

        return textView;
    }

    @Override
    // DropDownViewはスピナーを押したときに表示されるもの.これはそのままいじらない
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        TextView textView
                = (TextView)((LayoutInflater.from(getContext()).inflate(
                R.layout._spinner_dropdown, parent, false)));

        textView.setText(super.getItem(position)); // そのままいじらなくてもこれは明示しておく必要がある
        textView.setTextColor(Color.BLACK); // そのままいじらなくてもこれは明示しておく必要がある

        return textView;
    }

    //** Spinnerに表示されるTextViewの色を操作する **//
    public void setCustomTextViewColor( int newColor ) {
        textcolor = newColor;
    }
}

こちらを参考にさせて頂きました.
www.synapse.ne.jp
android-note.open-memo.net
qiita.com