华域联盟 Andriod Android小程序实现切换背景颜色

Android小程序实现切换背景颜色

本文实例为大家分享了Android实现切换背景颜色的具体代码,供大家参考,具体内容如下

(1)首先打开界面布局文件,添加两个Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

 <Button
 android:id="@+id/btnYellow"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="黄色"
 android:textColor="#fff"
 />
 <Button
 android:id="@+id/btnBlue"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="蓝色"
 android:textColor="#fff"
 />

</LinearLayout>

(2)在res/values目录下创建一个颜色资源文件color.xml

(3)编辑color.xml

<?xml version="1.0" encoding="UTF-8"?>
<resources>
 <color name="yellow">#ffee55</color>
 <color name="blue">#0000ff</color>
</resources>

(4)此时在R.java中自动生成color资源

(5)最后编写程序代码

package com.example.ch03;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 //声明两个按钮
 Button btnYellow;
 Button btnBlue;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 //根据Id找到界面中的两个按钮组件
 btnYellow=(Button)this.findViewById(R.id.btnYellow);
 btnBlue=(Button)this.findViewById(R.id.btnBlue);

 //注册监听器
 btnYellow.setOnClickListener(new OnClickListener(){
  public void onClick(View v){
  //设置背景颜色为黄色
  getWindow().setBackgroundDrawableResource(R.color.yellow);
  }
 });

 btnBlue.setOnClickListener(new OnClickListener(){
  public void onClick(View v){
  //设置背景颜色为蓝色
  getWindow().setBackgroundDrawableResource(R.color.blue);
  }
 });
 }
}

(6)结果展示

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » Android小程序实现切换背景颜色

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

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

作者: sterben

详解Android使用CoordinatorLayout+AppBarLayout+CollapsingToolbarLayou实现手指滑动效果

Android小程序实现音乐播放列表

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

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

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

微信扫一扫关注我们