如何在android中动态设置颜色透明?像10%20%到100%

时间:2018-05-28 11:29:47

标签: java android colors

我知道如何设置静态颜色,如#1Abf6116

    100% — FF
    95% — F2
    90% — E6
    85% — D9
    80% — CC
    75% — BF
    70% — B3
    65% — A6
    60% — 99
    55% — 8C
    50% — 80
    45% — 73
    40% — 66
    35% — 59
    30% — 4D
    25% — 40
    20% — 33
    15% — 26
    10% — 1A
    5% — 0D
    0% — 00

颜色代码=“#bf6116 ”  我想设置颜色 如果用户设置 10 而不是颜色#1Abf6116 如果用户设置 10%,如果用户设置为20%而不是我需要 33

,我希望获得 1a 等值

2 个答案:

答案 0 :(得分:1)

试试这个

//simple way to transparency set dynamicly any View 
TextView tv = findViewById(R.id.tv);
String has = "#";
String PR_transparency = "50";// this text background color 50% transparent;
String og_color = "FF001A";

tv.setBackgroundColor(Color.parseColor(has+PR_transparency+og_color));

答案 1 :(得分:0)

您可以创建地图:

//Initial color
String color = "#bf6116";

//Create a map which hold percent and its corresponding String
Map<Integer, String> mapPercent = Map.of(100, "FF", 95, "F2", 10, "1A");

//user input, to explain I use a static variable
int userInput = 10;
if(mapPercent.containsKey(userInput)) {
    //Use replaceFirst or subscring to put the corresponding String
    color = color.replaceFirst(
        "#(.*)", //the regex match # as group 1 and the rest as group 2
        //put the corresponding string between the two groups
        String.format("$0%s$1", mapPercent.get(userInput)) 
    );
}


System.out.println(color);//result in this case is #1Abf6116

注意:来自Java 10的Map.of,您可以使用普通的地图并输入