Android Studio中的颜色预览

11

有没有办法在编辑器窗口的左侧装订线看到以ARGB颜色定义为整数变量的颜色预览。我的意思是像注册资源一样的颜色预览。

enter image description here

这里有一张Photoshop处理过的截图,可以明确地展示我的意思。


Android Studio如何区分颜色值和其他类型的值?例如,当您编写“0x011”时,您是否期望看到某种颜色? - azizbekian
如果您设置了无效的颜色值,color.xml 中也可能会发生这种情况,它将不显示任何内容。我想知道是否有办法将此机制扩展到非资源变量! - ucMedia
2
据我所知,Android Studio不支持这个功能。我认为唯一的方法是开发自己的IntelliJ插件来实现这个功能。 - Enzokie
4个回答

6

3

如果您事先知道所有颜色,请将它们全部导入到colors.xml文件中,然后每次使用颜色时,它将始终显示在左侧。代码如下:

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

最终结果将会是这样的: enter image description here

3

对于int ARGB值,这是不可能的,因为IDE无法理解它们是颜色,它们可能只是数字。

另一方面,当您引用资源时,IDE可以在gutter中显示颜色预览,因为通过解析R.color.yourColor,IDE了解到它是一种颜色,而不是R.dimen或其他类型。

或者,您可以考虑编写一个Android Studio插件来实现所需的结果。


2

用javascript显示AndroidStudio的colors.xml文件

在此输入图片描述

我创建了一个名为scriptfile.html的文件,并将所有javascript放入其中,以便查看来自AndroidStudio的colors.xml整数变量的颜色预览。

我在scriptfile id="filexml"中粘贴了colors.xml,解析xml并生成具有以下内容的sam << div >>:color | hex | name

希望这可以帮到您:[编辑后的代码片段]

<!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>


阿塔,欢迎加入StackOverflow大家庭,并感谢你的回答。 - ucMedia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接