Color preview in Android Studio
Asked Answered
A

4

11

Is there a way to see the color preview of integer variables that defined as ARGB color in the left gutter of the Editor Window.
I mean something like the colors preview that registered as resource.

enter image description here

Here's a photoshopped screenshot which shows exactly what I mean.

Aldershot answered 5/4, 2018 at 8:6 Comment(3)
How would Android Studio differentiate whether that's a color value or some other type of value? For example, do you expect to see some color when you write 0x011?Riobard
It may happen in the color.xml too, if you set an invalidate color value, it shows nothing. I want to know is there any way to extend this mechanism to non resource variables!Aldershot
AFAIK this is not supported in Android Studio. I think the only way to do this is by developing your own IntelliJ plugin that does this.Convexoconcave
B
3

It's not possible for int ARGB values, because the IDE can't understand that they're colors, for they might be just numbers.

On the other hand, it can show the color preview in the gutter when you're referring to a resource because, parsing R.color.yourColor, the IDE understands that it's a color by the qualifier R.color rather than R.dimen or something.

Alternatively, you may look into writing a plugin for Android Studio in order to achieve the desired result.

Beitch answered 13/4, 2018 at 12:26 Comment(0)
T
6

It's only possible for the colors registered as resource (by the developer as in colors.xml or exists as some Android's resource).

Refer this link given below for more info.

Is there an easy way to see a color in Android Studio?

Transgression answered 9/4, 2018 at 12:53 Comment(0)
V
3

In the case you know all your colours beforehand, import all of them inside the colors.xml file and then each time you use a colour, it will always be displayed on the left. The code will look like this:

public static void obsidian(ucTheme theme) {
    theme.background_color = R.color.obsidian;
    theme.id = 1000;
}  

And the final result will be this: enter image description here

Voracious answered 13/4, 2018 at 12:4 Comment(0)
B
3

It's not possible for int ARGB values, because the IDE can't understand that they're colors, for they might be just numbers.

On the other hand, it can show the color preview in the gutter when you're referring to a resource because, parsing R.color.yourColor, the IDE understands that it's a color by the qualifier R.color rather than R.dimen or something.

Alternatively, you may look into writing a plugin for Android Studio in order to achieve the desired result.

Beitch answered 13/4, 2018 at 12:26 Comment(0)
A
2

show AndroidStudio colors.xml with javascript

enter image description here

I made a single scriptfile.html , [with all javascript in file includet] to see the color preview of integer variables from colors.xml from AndroidStudio.

I paste the colors.xml in one << div >> in the scriptfile id="filexml" , parse xml and make sam << div >> with: color | hex | name

Hope it helps: [ EDITed code snipped ]

<!DOCTYPE html><html><head><!-- https://www.hexcolortool.com/ XML to json: https://codeload.github.com/andrewhouser/xmlToJson/zip/master -->
<style>
/* whitespacenowrap _ parent */
.whitespacenowrap_parent {
    white-space: nowrap;
    /* border:1px solid yellow; */
    margin:0px;
    padding:0px;
}
/* inlineblock _ child */
.inlineblock_child {
    height: 17px;   
    display: inline-block;
    border-top: 1px solid silver; 
    margin:0px;
    padding-left:5px;
}
.width_hex_color{  width: 66px; }
.width_name{width: 473px; 
    /* border-top:0px; */
}
</style></head><body><h5 style="color:#FF9500; margin:2px;">AndroidStudio colors.xml &nbsp;
<span style="color:#33C458"> copy AndroidStudio colors.xml, to here, in this file, in <&lt;div id="filexml"&gt;>, and show Colors Hex and Names, dont need first line <&lt;?xml version="1.0" encoding="utf-8"?&gt;></span></h5>
<button onclick="show_colors_xml_Android_Studio()" >show_colors_xml_Android_Studio</button> 
<div id="color_div" ></div>
<pre><div id="outprn"></div></pre>

<pre><div id="temp_test_div_id">
        temp_test_div_id 
        <div class="whitespacenowrap_parent"><div class="inlineblock_child width_hex_color">1047</div><div class="inlineblock_child width_hex_color" style="background:#6C6C70;">&nbsp;</div><div class="inlineblock_child width_hex_color">#6C6C70</div><div class="inlineblock_child width_name">colorGray2c</div></div><div class="whitespacenowrap_parent"><div class="inlineblock_child width_hex_color">1048</div><div class="inlineblock_child width_hex_color" style="background:#48484A;">&nbsp;</div><div class="inlineblock_child width_hex_color">#48484A</div><div class="inlineblock_child width_name">colorGray3c</div></div>
        temp_test_div_id 
</div></pre>

<pre>

<!--    ##############################
          ############################ 
           ########################### 
            ########################## 
             ######################### 
              ######################## 
               ####################### 
        paste colors.xml AndroidStudio 
        in  div id="filexml" 
--><div id="filexml">



<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#545456</color>
<color name="colorPrimaryDark">#545456</color>
<color name="colorAccent">#fbd7bd</color>
<color name="colorDummyBeginOriginalAndroidStudioColors">#ff0bff</color>
<color name="colorPrimaryDarkAStudio">#3700B3</color>
<color name="colorPrimaryAStudio">#6200EE</color>
<color name="colorAccentAStudio">#03DAC5</color>
<color name="colorDummyEndOriginalAndroidStudioColors">#ff0eff</color>

 

 
<color name="colorGreenAccentAStudioa">#03DAC5</color>

<color name="colorWhiteGreenc">#addac5</color>
 
<color name="colorGreena">#33C458</color>
<color name="colorGreenc">#30D158</color>
<color name="colorGreenMidnighta">#4e5850</color>
<color name="colorGreenMidnightc">#004953</color>









<color name="colorBlueTeala">#5AC8FA</color>
<color name="colorBlueTealc">#64D2FF</color>
<color name="colorBluePantoned">#5EB0E5</color>

<color name="colorBluec">#0A84FF</color>
<color name="colorBluea">#007AFF</color>


<color name="colorBlueIndigoc">#5E5CE6</color>
<color name="colorBlueIndigoa">#5856D6</color>
<color name="colorBlueb">#0040DD</color>
<color name="colorBlueTealDarkd">#0071A4</color>



<color name="colorBlueDarkc">#010f8a</color>


<color name="colorBlueIndigoDarkb">#3634A3</color>




<color name="colorBluePrimaryDarkAStudioa">#3700B3</color>

<color name="colorBluePurpleb">#8944AB</color>
<color name="colorBluePurpleVioletDark">#8944AB</color>


<color name="colorBluePurplec">#BF5AF2</color>
<color name="colorBluePurplea">#AF52DE</color>







<color name="colorPinkd">#FF6482</color>
<color name="colorRedsystemc">#FF453A</color>
<color name="colorPinka">#FF375F</color>
<color name="colorRedsystema">#FF3B30</color>
<color name="colorPinkc">#FF375F</color>
<color name="colorPinkb">#D30F45</color>
<color name="colorRedPantonee">#BA0C2E</color>
<color name="colorGraySpacegraySilverc">#52514f</color>
<color name="colorGraySilverc">#52514f</color>





<color name="colorGrayb">#6C6C70</color>
<color name="colorGray2a">#8E8E93</color>


<color name="colorGray3b">#AEAEB2</color>
<color name="colorGray3a">#C7C7CC</color>

<color name="colorGray4a">#D1D1D6</color>
<color name="colorGray5a">#E5E5EA</color>

<color name="colorGrey6b">#EBEBF0</color>
<color name="colorGrey6a">#F2F2F7</color>









    


<color name="colorWhitePantonec">#F9F6EF</color>

<color name="colorGraySilverSystemc">#ebebef</color>

<color name="colorGraySilverSystema">#ebebe3</color>

<color name="colorSilverPantonea">#E4E4E2</color>
<color name="colorGrayc">#98989D</color>


<color name="colorGraya">#8E8E93</color>

<color name="colorGray2c">#6C6C70</color>
<color name="colorGray3d">#545456</color>
<color name="colorGray3c">#48484A</color>

<color name="colorGray4c">#3A3A3C</color>
<color name="colorGray5c">#2C2C2E</color>
<color name="colorGrey6c">#1C1C1E</color>

<color name="colorGrey6d">#242426</color>



<color name="colorGolde">#fbd7bd</color>
<color name="colorGoldRosePantoneb">#E6C7C2</color>


<color name="colorWhiteRosea">#dbc1ef</color>


<color name="colorYellowa">#FFCC00</color>
<color name="colorYellowc">#FFD60A</color>


<color name="colorRoseBrowna">#de9e95</color>

<color name="colorGoldYellowBrowna">#b69221</color>

<color name="colorOrangea">#FF9500</color>
<color name="colorOrangeb">#FF9500</color>

</resources>


</div><!-- filexml end  
        paste colors.xml AndroidStudio 
        in  div id="filexml" above
              ########################
             #########################
            ##########################
           ###########################
          ############################
         #############################
        ##############################
-->


<div id="outprn1"></div>
<div id="outprn2"></div>
<div id="outprn3"></div>
<div id="outprn4"></div>
<div id="outprn5"></div>
<div id="outprn6"></div>


<script type="text/javascript">
var filexml_is_empty=0;
// on buttn click, or window.onload fires when the entire page loads (images, styles, etc.) :
// 
window.onload = 
function show_colors_xml_Android_Studio() {

    if(filexml_is_empty)return;  

    var debug=false; // console help search: if(debug)

    var str = document.getElementById("filexml").innerHTML;
    document.getElementById("temp_test_div_id").innerHTML="";   
    document.getElementById("filexml").innerHTML="";
    filexml_is_empty=1;
    //clean string str because error in xmlToJson.parse()
    // console.log("String ori: ", str);
    strH = str.toHtmlEntitiesRemoveBadXMLchars();
    // console.log("str toEntities: ", str);
    str = String.fromHtmlEntities(strH);
    // String is class obj ?
    // console.log("clean from htmlentities:", String.fromHtmlEntities(str));  
    //
    // strip xml header because error in strg xml to json xmlToJson.parse()
    str = str.match(/\<resources([^\]]*)resources\>/);
    // document.getElementById("outprn3").innerHTML = str;
    // console.log("match  str obj:", str);
    // regex match in first str[0]
    str=str[0];     
    var json = xmlToJson.parse( str );
    // console.log("json: ", json);
    
    /***/
    if(debug){  
        document.getElementById("outprn3").innerHTML='<br><h3>strH.toHtmlEntities: </h3>'+ strH;
        var jsonstr = JSON.stringify(json);
        jsonstr=jsonstr.replace(/\[/gm,",[<br><br>    "); 
        jsonstr=jsonstr.replace(/\]/gm,",<br>    ]<br>"); 
        jsonstr=jsonstr.replace(/,/gm,",<br>    ");
        document.getElementById("outprn4").innerHTML='<br><h3>jsonstr:</h3>'+ jsonstr;
        console.log("match parse:", jsonstr);
        console.log("str:", str);
        console.log("json[0]", json[0]); // erster char!!!!!
        console.log('json["resources"]: ', json["resources"] );//color: array 3
        console.log("json.resources: ", json.resources );
        console.log("json.resources.color: ", json.resources.color );
        console.log("json.resources.color[0]: ", json.resources.color[0] );
        console.log("json.resources.color[0].name: ", json.resources.color[0].name );
        console.log("json.resources.color[0].text: ", json.resources.color[0].text );
        console.log("json.resources.color[1].name: ", json.resources.color[1].name );
        console.log("json.resources.color[1].text: ", json.resources.color[1].text );
        console.log("json.resources.color[2].name: ", json.resources.color[2].name );
        console.log("json.resources.color[2].text: ", json.resources.color[2].text );
        //console.log("json.resources.color[0][0]: ", json.resources.color[0][0] ); //undef
        //console.log("json.resources.color.name: ", json.resources.color.name ); //undef
    }
    /***/
    console.log('Object.keys(json).length: ', Object.keys(json.resources.color).length )// 3
    document.getElementById("outprn").innerHTML=' &nbsp; <small > Object.keys(json).length: '+ Object.keys(json.resources.color).length +'</small>';


    var cdiv = document.getElementById("color_div").innerHTML;
    n=Object.keys(json.resources.color).length;
    // test XML problem:
    //  n=n+2; //ok, til error, todo: error check
    for(let i=0; i<n; i++){ 
        cdiv += color_num(i, json);
        // ok function til ERROR and show htm til error
        document.getElementById("color_div").innerHTML = cdiv;
    }   


        
    
    
 
}
// ver_2 color name text move to right
function color_num(n, json){
    
    var color_div ='<div  class="whitespacenowrap_parent">';
    
    /* add line number 100+n  /***/
    color_div+='<div class="inlineblock_child width_hex_color" >';
    color_div+=1001+n;
    color_div+='</div>';
    /***/
    color_div+='<div class="inlineblock_child width_hex_color" style="background:';
    color_div+=json.resources.color[ n ].text;
    color_div+=';">&nbsp;</div><div class="inlineblock_child width_hex_color">';        
    color_div+=json.resources.color[ n ].text;
    color_div+='</div><div class="inlineblock_child width_name">';
    color_div+=b6=json.resources.color[ n ].name;
    color_div+='</div></div>';
    return  color_div;  

    
}


/**
 * Convert a string to HTML entities , ORIGINAL
 */
String.prototype.toHtmlEntities = function() {
    return this.replace(/[\s\S]/gm, function(s) {
    // return this.replace(/./gm, function(s) {
        //  \s  Find a whitespace character
        //  \S  Find a non-whitespace character
        // return "&#" + s.charCodeAt(0) + ";";
        return (s.match(/[a-z0-9\s]+/i)) ? s : "&#" + s.charCodeAt(0) + ";";
    });
};
// add strip bad xml chars
// Where he links to this article: http://www.w3.org/TR/xml/#charsets
// Basically, all characters below 0x20 is disallowed, 
// except 0x9 (TAB), 0xA (CR?), 0xD (LF?) 
String.prototype.toHtmlEntitiesRemoveBadXMLchars = function() {
        //  \s  Find a whitespace character
        //  \S  Find a non-whitespace character       [\s\S]
    //return this.replace(/./gm, function(s) {    // [\s\S]
    return this.replace(/[\s\S]/gm, function(s) {
        // return "&#" + s.charCodeAt(0) + ";";
        //add
        var q=s.charCodeAt(0);
        return (s.match(/[a-z0-9\s]+/i)) ? s :          
            s=
            (
            
                q== 0x9 ||  q== 0xA || q== 0xD || 
                ((q>= 0x20) && (q<= 0xD7FF)) ||
                ((q>= 0xE000) && (q<= 0xFFFD)) ||
                ((q>= 0x10000) && (q<= 0x10FFFF ))
                
            )?  
            
                "&#" + s.charCodeAt(0) + ";"
                
            :  
            
                ""  
                
            ;       
    });
};


/**
 * Create string from HTML entities
 */
String.fromHtmlEntities = function(string) {
    return (string+"").replace(/&#\d+;/gm,function(s) {
        return String.fromCharCode(s.match(/\d+/gm)[0]);
    })
};

</script></pre>


<!-- 
    this min version do not work here for me,
    so I copy  xmlToJson.js to the end
-  ->
<script type="text/javascript">if(typeof Object.assign!="function"){Object.defineProperty(Object,"assign",{value:function assign(r,n){"use strict";if(r==null){throw new TypeError("Cannot convert undefined or null to object")}var t=Object(r);for(var e=1;e<arguments.length;e++){var i=arguments[e];if(i!=null){for(var f in i){if(Object.prototype.hasOwnProperty.call(i,f)){t[f]=i[f]}}}}return t},t:true,i:true})}var xmlToJson=function(){var r=this;r.u=function(r,n,t){if(!r[n]){r[n]=t}else{if(!Array.isArray(r[n])){var e=r[n];r[n]=[];r[n].push(e)}r[n].push(t)}};r.o=function(r){var n=null;if(r&&typeof r==="string"){var t=new DOMParser;n=t.parseFromString(r,"application/xml")}return n};r.l=function(r){var n=(r?r.ownerDocument||r:0).documentElement;return n?n.nodeName.toLowerCase()!=="html":false};r.s=function(n){var t=n.attributes,e={};if(n.hasAttributes()){for(var i=0;i<t.length;i++){e[t[i].name]=r.v(t[i].value)}}return e};r.j=function(n,t){if(t.length>0){for(var e=0;e<t.length;e++){if(t[e].nodeType==1){r.p(n,t[e])}}}};r.p=function(n,t){var e=t.nodeName,i=Object.assign({},r.s(t)),f=null;if(t.childNodes.length==1&&t.childNodes[0].nodeType==3){if(t.hasAttributes()){i["text"]=r.v(t.childNodes[0].nodeValue)}else{i=r.v(t.childNodes[0].nodeValue)}}else{r.j(i,t.childNodes)}r.u(n,e,i);return n};this.v=function(r){var n=Number(r);if(r.toLowerCase()==="true"||r.toLowerCase()==="false"){return r.toLowerCase()=="true"?true:false}return isNaN(n)?r:r.length==0?null:n};return{parse:function(n){if(n&&typeof n==="string"){
n=this.o(n)}return n&&r.l(n)?r.p({},n.firstChild):null}}}();</script><!-- error this.o is not a function -->


<!-- -  -><script type="text/javascript" src="xmlToJson.js"></script><!-- -->
<script type="text/javascript">
/**
<!--

    https://www.hexcolortool.com/
    
    XML to json download 
    
    https://codeload.github.com/andrewhouser/xmlToJson/zip/master 

-->
*/
/**
* Object assign is required, so ensure that browsers know how to execute this method
*
* @method Object.assign
* @returns {Function}
*/
if (typeof Object.assign != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}


/**
* Object to convert XML into a structured JSON object
*
* @method xmlToJson
* @returns {Object}
*/
var xmlToJson = (function () {
  var self = this;


    /**
    * Adds an object value to a parent object
    *
    * @method addToParent
    * @param {Object} parent
    * @param {String} nodeName
    * @param {Mixed} obj
    * @returns none
    */
  self.addToParent = function (parent, nodeName, obj) {
    // If this is the first or only instance of the node name, assign it as
    // an object on the parent.
    if (!parent[nodeName]) {
      parent[nodeName] = obj;
    }
    // Else the parent knows about other nodes of the same name
    else {
      // If the parent has a property with the node name, but it is not an array,
      // store the contents of that property, convert the property to an array, and
      // assign what was formerly an object on the parent to the first member of the
      // array
      if (!Array.isArray(parent[nodeName])) {
        var tmp = parent[nodeName];
        parent[nodeName] = [];
        parent[nodeName].push(tmp);
      }

      // Push the current object to the collection
      parent[nodeName].push(obj);
    }
  };




  self.convertXMLStringToDoc = function (str) {
    var xmlDoc = null;

    if (str && typeof str === 'string') {
      // Create a DOMParser
      var parser = new DOMParser();

      // Use it to turn your xmlString into an XMLDocument
      xmlDoc = parser.parseFromString(str, 'application/xml');
    }

    return xmlDoc;
  }


    /**
    * Validates if an data is an XMLDocument
    *
    * @method isXML
    * @param {Mixed} data
    * @returns {Boolean}
    */
  self.isXML = function (data) {
    var documentElement = (data ? data.ownerDocument || data : 0).documentElement;

    return documentElement ? documentElement.nodeName.toLowerCase() !== 'html' : false;
  };


    /**
    * Reads through a node's attributes and assigns the values to a new object
    *
    * @method parseAttributes
    * @param {XMLNode} node
    * @returns {Object}
    */
  self.parseAttributes = function (node) {
    var attributes = node.attributes,
      obj = {};

    // If the node has attributes, assign the new object properties
    // corresponding to each attribute
    if (node.hasAttributes()) {
      for (var i = 0; i < attributes.length; i++) {
        obj[attributes[i].name] = self.parseValue(attributes[i].value);
      }
    }

    // return the new object
    return obj;
  };


    /**
    * Rips through child nodes and parses them
    *
    * @method parseChildren
    * @param {Object} parent
    * @param {XMLNodeMap} childNodes
    * @returns none
    */
  self.parseChildren = function (parent, childNodes) {
    // If there are child nodes...
    if (childNodes.length > 0) {
      // Loop over all the child nodes
      for (var i = 0; i < childNodes.length; i++) {
        // If the child node is a XMLNode, parse the node
        if (childNodes[i].nodeType == 1) {
          self.parseNode(parent, childNodes[i]);
        }
      }
    }
  };


    /**
    * Converts a node into an object with properties
    *
    * @method parseNode
    * @param {Object} parent
    * @param {XMLNode} node
    * @returns {Object}
    */
  self.parseNode = function (parent, node) {
    var nodeName = node.nodeName,
      obj = Object.assign({}, self.parseAttributes(node)),
      tmp = null;

    // If there is only one text child node, there is no need to process the children
    if (node.childNodes.length == 1 && node.childNodes[0].nodeType == 3) {
      // If the node has attributes, then the object will already have properties.
      // Add a new property 'text' with the value of the text content
      if (node.hasAttributes()) {
        obj['text'] = self.parseValue(node.childNodes[0].nodeValue);
      }
      // If there are no attributes, then the parent[nodeName] property value is
      // simply the interpreted textual content
      else {
        obj = self.parseValue(node.childNodes[0].nodeValue);
      }
    }
    // Otherwise, there are child XMLNode elements, so process them
    else {
      self.parseChildren(obj, node.childNodes);
    }

    // Once the object has been processed, add it to the parent
    self.addToParent(parent, nodeName, obj)

    // Return the parent
    return parent;
  };


    /**
    * Interprets a value and converts it to Boolean, Number or String based on content
    *
    * @method parseValue
    * @param {Mixed} val
    * @returns {Mixed}
    */
  this.parseValue = function (val) {
    // Create a numeric value from the passed parameter
    var num = Number(val);

    // If the value is 'true' or 'false', parse it as a Boolean and return it
    if (val.toLowerCase() === 'true' || val.toLowerCase() === 'false') {
      return (val.toLowerCase() == 'true');
    }

    // If the num parsed to a Number, return the numeric value
    // Else if the valuse passed has no length (an attribute without value) return null,
    // Else return the param as is
    return (isNaN(num)) ? val.trim() : (val.length == 0) ? null : num;
  };

  // Expose the API
  return {
    parse: function (xml) {
      if (xml && typeof xml === 'string') {
        xml = self.convertXMLStringToDoc(xml);
      }
      return (xml && self.isXML(xml)) ? self.parseNode({}, xml.firstChild) : null;
    }
  }
})();

</script>
</body></html>
Acotyledon answered 11/7, 2020 at 21:20 Comment(1)
Ata welcome to the stackoverflow family and thanks for the answerAldershot

© 2022 - 2024 — McMap. All rights reserved.