Android小程序?qū)崿F(xiàn)切換背景顏色
更新時間:2020年05月22日 15:47:03 作者:adorable_
這篇文章主要介紹了Android小程序?qū)崿F(xiàn)切換背景顏色,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Android實現(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="藍色" 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è)置背景顏色為藍色 getWindow().setBackgroundDrawableResource(R.color.blue); } }); } }
(6)結(jié)果展示
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Kotlin自定義View系列教程之標尺控件(選擇身高、體重等)的實現(xiàn)
這篇文章主要給大家介紹了關(guān)于Kotlin自定義View系列教程之標尺控件(選擇身高、體重等)實現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧2018-07-07android studio錯誤: 常量字符串過長的解決方式
這篇文章主要介紹了android studio錯誤: 常量字符串過長的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04