android中colors.xml颜色设置资源文件

1. 打开res目录下的values文件夹,双击打开colors.xml文件进行编辑

在这里插入图片描述
上代码

<?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. 在res目录下的layout文件夹创建color_layout.xml文件

在这里插入图片描述

在这里插入图片描述

下述代码演示如何在XML文件中访问颜色.

上代码

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

上述代码中@color/color_xml 为XML文件读取colors.xml文件中名为color_xml的RGB颜色代码,并将该颜色以 Text View的形式显示出来。

3. 在java目录下的com.example.myapplication包中创建Color_ActivityDemo类

在这里插入图片描述
在这里插入图片描述

下述代码演示如何在Java代码中访问颜色。

上代码

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));
    }
}

上述代码中getResources ().getColor(R.color.color _java)为Java代码读取colors.xml文件中名为color_java的 RGB颜色代码,并将该颜色以TextView的形式显示出来。

4. 在AndroidMainfest.xml文件添加Color_ActivityDemo.java的列表

在这里插入图片描述在这里插入图片描述

5. 运行Color_ActivityDemo.java

在这里插入图片描述

运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42768634/article/details/115048218