Article Directory
- 1. Open the values folder in the res directory, double-click to open the colors.xml file for editing
- 2. Create a color_layout.xml file in the layout folder under the res directory
- 3. Create the Color_ActivityDemo class in the com.example.myapplication package under the java directory
- 4. Add the list of Color_ActivityDemo.java to the AndroidMainfest.xml file
- 5. Run Color_ActivityDemo.java
1. Open the values folder in the res directory, double-click to open the colors.xml file for editing
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
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
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
5. Run Color_ActivityDemo.java
operation result