Javaコードのさまざまな状態でDrawableまたはTextViewのフォントを動的に変更します

// 1.Drawableを使用する 


private Drawable getDrawable(String rootPath, String home_unselect, String home_select) {
    try {
        Drawable unselectDrawable= Drawable.createFromPath(rootPath + "/" + home_unselect);
        Drawable selectDrawable= Drawable.createFromPath(rootPath + "/" + home_select);
        StateListDrawable drawable = new StateListDrawable();
        drawable.addState(new int[]{android.R.attr.state_selected}, chooseDrawable);
        drawable.addState(new int[]{-android.R.attr.state_selected}, initDrawable);
        return drawable;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;

}

// 2.Drawableを設定する

Drawable home = getDrawable(rootPath, home_unselect, home_select)
home .setBounds(1, 1, 66, 66);
TextView homeTextview = ftbHome.getTabWidget().getChildTabViewAt(0).findViewById(R.id.tabDrawable);
homeTextview.setCompoundDrawables(null, home, null, null);

// 1。フォントの色を取得する

int unSelect = formatFontColor(P5_FONT_NORMAL);
int select = formatFontColor(P5_FONT_WARN());
if (unSelect != -1 && select != -1) {
    int[] colors =new int[] { unSelect, select};
    int[][] states =new int[2][];
    states[0] =new int[] { -android.R.attr.state_selected};
    states[1] =new int[] { android.R.attr.state_selected};

    ColorStateList colorStateList =new ColorStateList(states,colors);
 
        TextView viewById = ftbHome.getTabWidget().getChildTabViewAt(i).findViewById(R.id.name);
        viewById.setTextColor(colorStateList);
    
}

 

//颜色转换
public int formatFontColor(String p1_font_normal) {
    int color = -1;
    if (TextUtils.isEmpty(p1_font_normal)||"null".equals(p1_font_normal))return -1;
    if (p1_font_normal.startsWith("rgba")){
        color = rgbaToHexColor(p1_font_normal);
    }else  if (p1_font_normal.startsWith("rgb")){
        String[] rgbs = p1_font_normal.replaceAll("rgb", "")
                .replaceAll("\\(", "")
                .replaceAll("\\)", "")
                .replaceAll(" ","").split(",");
        if (rgbs.length==3){
            color = Color.rgb(Integer.parseInt(rgbs[0]),
                    Integer.parseInt(rgbs[1]),
                    Integer.parseInt(rgbs[2]));
        }
    }else if (p1_font_normal.startsWith("#")){
        color =  Color.parseColor(p1_font_normal);
    }

    return color ;
}

//rgba受api限制做此转换
private int rgbaToHexColor(String color) {
    String[] rgbs = color.replaceAll("rgba", "")
            .replaceAll("\\(", "")
            .replaceAll("\\)", "")
            .replaceAll(" ", "").split(",");
    int color111 = Color.rgb(Integer.parseInt(rgbs[0]),
            Integer.parseInt(rgbs[1]),
            Integer.parseInt(rgbs[2]));

    int v = (int) (Float.parseFloat(rgbs[3]) * 255);
    String s = Integer.toHexString(color111).substring(2);
    String hex = "#"+Integer.toHexString(v)+s;
    return Color.parseColor(hex);

}

おすすめ

転載: blog.csdn.net/lk2021991/article/details/90256606