手撕代碼之java代碼實現selector和shape

習慣了用xml佈局的方式設置顏色、圖片的選擇器,有的時候需要跟靈活的動態設置,這個時候就會想到用代碼直接實現,下面分享一下。

一、設置color選擇器

color對應的是ColorStateList

一般用xml實現如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/color_666666" android:state_selected="false" />
    <item android:color="@color/color_999999" android:state_selected="true" />
</selector>

用代碼實現如下:

        int[] colors = new int[]{0xff999999, 0xff666666};//對應分別對應states[0][],states[1][]
        int[][] states = new int[2][];
        states[0] = new int[]{android.R.attr.state_selected};//設置選擇
        states[1] = new int[]{};
        ColorStateList defaultTextColorSelector = new ColorStateList(states, colors);
        textView.setTextColor(defaultTextColorSelector);

二、設置drawable選擇器

 

drawable對應的是StateListDrawable

一般xml實現如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_bottom_tab1_unselected" android:state_selected="false" />
    <item android:drawable="@drawable/icon_bottom_tab1_selected" android:state_selected="true" />
</selector>

 

用代碼實現如下:

 

        StateListDrawable mBgStateListDrawable = new StateListDrawable();
        mBgStateListDrawable.addState(new int[]{android.R.attr.state_selected}, getResources().getDrawable(R.drawable.icon_bottom_tab1_selected));
        mBgStateListDrawable.addState(new int[]{-android.R.attr.state_selected}, getResources().getDrawable(R.drawable.icon_bottom_tab1_unselected));

        final TextView textView = findViewById(R.id.hello);
        textView.setBackgroundDrawable(mBgStateListDrawable);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setSelected(!textView.isSelected());
            }
        });

需要注意添加state是有序的,會按順序判斷最先符合條件的state,如果把最大範圍的state放在最前面,後面的將不會執行,此外,在添加state中,在state前添加“-”號,表示此state爲false(例如:-android.R.attr.state_selected),否則爲true。

三、代碼設置shape

 

        int strokeWidth = 5; // 3dp 邊框寬度
        int roundRadius = 15; // 8dp 圓角半徑
        int strokeColor = Color.parseColor("#2E3135");//邊框顏色
        int fillColor = Color.parseColor("#DFDFE0");//內部填充顏色

        GradientDrawable gd = new GradientDrawable();//創建drawable
        gd.setColor(fillColor);
        gd.setCornerRadius(roundRadius);
        gd.setStroke(strokeWidth, strokeColor, 30, 15);
        gd.setShape(GradientDrawable.OVAL);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章