【问题标题】:Change background Color with hexdecimal用十六进制更改背景颜色
【发布时间】:2016-04-02 16:10:49
【问题描述】:

在 mainActivity 中,我使用 hexString 然后开始新的活动并将 hexString 发送给它 并使用此十六进制字符串更改背景颜色。 我需要知道是否有背景颜色方法可以带参数 hexString 或 long 。

代码:

String colorValue = getIntent().getStringExtra("colorHex");
findViewById(R.id.layout1).setBackgroundColor(Color.parseColor(colorValue));//want change in the argument or if there's another method.

【问题讨论】:

    标签: android android-activity colors hex


    【解决方案1】:

    Google Documentation

    尝试使用函数public static int parseColor (String colorString) 这需要一个字符串并返回 int 颜色!

    解析颜色字符串,返回对应的颜色整数。如果无法解析字符串,则抛出 IllegalArgumentException 异常。支持的格式是:#RRGGBB #AARRGGBB 或以下名称之一:'red'、'blue'、'green'、'black'、'white'、'gray'、'cyan'、'magenta'、'yellow' ,“浅灰色”,“深灰色”,“灰色”,“浅灰色”,“深灰色”,“浅绿色”,“紫红色”,“石灰”,“栗色”,“海军”,“橄榄色”,“紫色”,“银','蓝绿色'。

    试试这样的

    //find your layout
    LinearLayout ll = (LinearLayout) findViewById(R.id.yourLinearLayout);
    
    //Get the color from an EditText
    EditText newcolor = (EditText) findViewById(R.id.yourEditText);
    String stringColor = newcolor.getText().toString(): //Assume that you have the #RRGGBB
    
    //the function take only #RRGGBB with 6 values read documentation for more information
     int intColor = Color.parseColor(stringColor);
    
    //Set the color to the LinearLayout
    ll.setBackground(intColor); 
    

    【讨论】:

    • 如果我插入十六进制 ex 0xfff,它会停止新活动。
    • try with #, like this public static int parseColor("#0xfff") 使用 try 和 catch 因为 如果字符串无法解析,则抛出 IllegalArgumentException 异常
    • 当它开始新的活动时仍然会下来。
    • 你说的是应用崩溃了,当它崩溃时你可以在logcat中找到错误,当应用崩溃时复制并粘贴错误。
    • 并发布更多代码,不仅是 2 行,以便我和其他用户可以提供更多帮助。
    【解决方案2】:

    假设颜色为黄色。

    private static int yellow = Color.parseColor("#f9ce1e");
    view.setBackgroundColor(yellow);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多