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)