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

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

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

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

adorable_   2020-05-22 我要评论

本文实例为大家分享了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)结果展示

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

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