华域联盟 Andriod android中colors.xml颜色设置资源文件的方法

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

运行结果

到此这篇关于android中colors.xml颜色设置资源文件的文章就介绍到这了,更多相关android中colors.xml颜色内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

本文由 华域联盟 原创撰写:华域联盟 » android中colors.xml颜色设置资源文件的方法

转载请保留出处和原文链接:https://www.cnhackhy.com/109125.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们