android colors.xml color setting resource file

1. Open the values ​​folder in the res directory, double-click to open the colors.xml file for editing

Insert picture description here
Upload code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
    <color name="color_xml">#ff0000</color>
    <color name="color_java">#0000ff</color>
</resources>

2. Create a color_layout.xml file in the layout folder under the res directory

Insert picture description here

Insert picture description here

The following code demonstrates how to access colors in an XML file.

Upload code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text = "XML文件访问colors资源(红色)"
        android:id = "@+id/tv3"
        android:textColor="@color/color_xml" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text = "Java文件访问colors资源(蓝色)"
        android:id = "@+id/tv4" />
</LinearLayout>

In the above code, @color/color_xml reads the RGB color code named color_xml in the colors.xml file for the XML file, and displays the color in the form of Text View.

3. Create the Color_ActivityDemo class in the com.example.myapplication package under the java directory

Insert picture description here
Insert picture description here

The following code demonstrates how to access colors in Java code.

Upload code

package com.example.myapplication;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class Color_ActivityDemo extends AppCompatActivity {
    
    
    TextView tv4;
    public void onCreate(Bundle saveInstanceState) {
    
    
        super.onCreate(saveInstanceState);
        setContentView(R.layout.color_layout);
        tv4 = (TextView) findViewById(R.id.tv4);
        tv4.setTextColor(getResources().getColor(R.color.color_java));
    }
}

In the above code, getResources ().getColor(R.color.color _java) reads the RGB color code named color_java in the colors.xml file for Java code, and displays the color in the form of TextView.

4. Add the list of Color_ActivityDemo.java to the AndroidMainfest.xml file

Insert picture description hereInsert picture description here

5. Run Color_ActivityDemo.java

Insert picture description here

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/115048218