Android小程序?qū)崿F(xiàn)切換背景顏色
本文實(shí)例為大家分享了Android實(shí)現(xiàn)切換背景顏色的具體代碼,供大家參考,具體內(nèi)容如下
(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="藍(lán)色" android:textColor="#fff" /> </LinearLayout>

(2)在res/values目錄下創(chuàng)建一個顏色資源文件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);
//根據(jù)Id找到界面中的兩個按鈕組件
btnYellow=(Button)this.findViewById(R.id.btnYellow);
btnBlue=(Button)this.findViewById(R.id.btnBlue);
//注冊監(jiān)聽器
btnYellow.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//設(shè)置背景顏色為黃色
getWindow().setBackgroundDrawableResource(R.color.yellow);
}
});
btnBlue.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//設(shè)置背景顏色為藍(lán)色
getWindow().setBackgroundDrawableResource(R.color.blue);
}
});
}
}
(6)結(jié)果展示

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)帶圖標(biāo)的列表對話框
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)帶圖標(biāo)的列表對話框,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
Android 多線程實(shí)現(xiàn)重復(fù)啟動與停止的服務(wù)
這篇文章主要介紹了Android 多線程實(shí)現(xiàn)重復(fù)啟動與停止的服務(wù)的相關(guān)資料,多線程環(huán)境下為了避免死鎖,一般提倡開放調(diào)用,開放調(diào)用可以避免死鎖,它的代價是失去原子性,這里說明重復(fù)啟動與停止的服務(wù),需要的朋友可以參考下2017-08-08
Kotlin自定義View系列教程之標(biāo)尺控件(選擇身高、體重等)的實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于Kotlin自定義View系列教程之標(biāo)尺控件(選擇身高、體重等)實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07
Android自定義控件之圓形/圓角的實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了Android自定義控件之圓形/圓角的實(shí)現(xiàn)代碼,感興趣的小伙伴們可以參考一下2016-03-03
android studio錯誤: 常量字符串過長的解決方式
這篇文章主要介紹了android studio錯誤: 常量字符串過長的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Android 靜默安裝和智能安裝的實(shí)現(xiàn)方法
靜默安裝就是無聲無息的在后臺安裝apk,沒有任何界面提示。智能安裝就是有安裝界面,但全部是自動的,不需要用戶去點(diǎn)擊。下面腳本之家小編給大家介紹下Android 靜默安裝和智能安裝的實(shí)現(xiàn)方法,感興趣的朋友一起看看吧2018-01-01

