代码设置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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值