1. 程式人生 > >程式碼設定selector和color

程式碼設定selector和color

selector相關===StateListDrawable

color相關====ColorStateList

程式碼:

package com.example.checked;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.StateListDrawable;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class MyActivity extends Activity {
    CheckBox check;
    TextView text;
    ImageView image1,image2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        check = (CheckBox) findViewById(R.id.check);
        StateListDrawable bg = new StateListDrawable();     //程式碼設定背景selector
        bg.addState(new int[]{android.R.attr.state_checked}, getResources().getDrawable(R.drawable.main_01_press));
        bg.addState(new int[]{}, getResources().getDrawable(R.drawable.main_01_normal));
        check.setBackground(bg);

        text = (TextView) findViewById(R.id.text);
//        int[][] states = new int[2][];
        int[][] states = new int[2][];
        states[0] =  new int[]{android.R.attr.state_pressed};
        states[1] = new int[]{};
        int[] colors = new int[]{0xffaabbcc,0xff000000};    //0xffaabbcc跟states[0]對應,0xff000000跟states[1]對應,以此類推
        ColorStateList csl = new ColorStateList(states,colors);
        text.setTextColor(csl);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.main_01_press);
        image1 = (ImageView) findViewById(R.id.image1);
        //new BitmapDrawable(bitmap)過時api,不會基於目標裝置的密度生成drawable
        image1.setBackground(new BitmapDrawable(bitmap));

        image2 = (ImageView) findViewById(R.id.image2);
        //new BitmapDrawable(getResources(),bitmap)基於目標裝置的密度生成drawable
        image2.setBackground(new BitmapDrawable(getResources(),bitmap));
    }
}
效果圖:



對於資原始檔來設定的話,color選擇器放到res的color資源目錄下,drawable仿res的drawable下

原始碼:http://yunpan.cn/cmtI6wivD9WDm (提取碼:a9ed)