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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

你要永远相信光z   2021-03-23 我要评论
想了解android中colors.xml颜色设置资源文件的方法的相关内容吗,你要永远相信光z在本文为您仔细讲解android中colors.xml颜色的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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

在这里插入图片描述

运行结果

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们