Switch background color of Android applet

(1) First open the interface layout file and add two Buttons

<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>

describe

(2) Create a color resource file color.xml in the res/values ​​directory

describe

describe

(3) Edit color.xml

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

(4) At this time, the color resource is automatically generated in R.java

describe

(5) Finally write the program code

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) Result display

describe

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325527820&siteId=291194637