【问题标题】:Get Background Color of a View in hex以十六进制获取视图的背景颜色
【发布时间】:2018-06-06 17:02:54
【问题描述】:

我想以十六进制格式获取视图的背景颜色。

例如考虑int getViewBackgroundColor(View view)我的例外返回值是0Xff256e78

我该怎么做?

谢谢。

【问题讨论】:

    标签: android user-interface view colors background


    【解决方案1】:

    以下代码将获取视图的背景颜色并将其转换为颜色的 int 表示形式。

    ColorDrawable buttonColor = (ColorDrawable) myView.getBackground();
    int colorId = buttonColor.getColor();
    

    【讨论】:

      【解决方案2】:
      LinearLayout layout = (LinearLayout) findViewById(R.id.lay1);
      ColorDrawable viewColor = (ColorDrawable) layout.getBackground();
      int colorId = viewColor.getColor();
      

      得到整数类型的颜色后,现在必须转换为十六进制:

      String hexColor = String.format("#%06X", (0xFFFFFF & colorId));
      

      希望这会有所帮助..

      【讨论】:

      • 感谢它的工作,但它是 String ,让它长 -> Long.parseLong(hexColorString, 16)
      【解决方案3】:

      这是 Kotlin 语言的答案:

      var view: View = findViewById(R.id.bg_view_id)
      var draw: ColorDrawable = view.background as ColorDrawable
      var color_id = draw.getColor()
      
      Log.i("UYARI-INFO: ", Integer.toHexString(color_id))
      

      Logcat 中的输出将是:

      I/UYARI-INFO:: ffffd8af
      

      【讨论】:

        猜你喜欢
        • 2017-06-25
        • 2012-09-21
        • 1970-01-01
        • 2019-07-20
        • 2015-06-23
        • 2014-03-03
        • 2011-08-25
        • 2016-04-02
        • 2010-10-12
        相关资源
        最近更新 更多