Android变脸——主题(Theme)的实现
Android有了Style(模式)的设计概念后,程序员可以专注于业务逻辑,而视觉设计人员更可掌握手机程序里的视觉模式;现在除了Style的制定功能外,Android更可以针对每个Activity、前景、背景,以及透明度等进行设置。下面以一个简单的程序对Theme(主题)做一下介绍:
首先在res/values/style.xml中加入如下代码:
<?xmlversion="1.0" encoding="utf-8"?>
<resourcesxmlns:android="http://schemas.android.com/apk/res/android">
<!-- 基础应用程序主题,为默认主题 -->
<style name="Theme"parent="android:Theme"></style>
<!-- 更改应用程序的主题,使之具有透明背景 -->
<style name="Theme.Translucent">
<itemname="android:windowBackground">@android:color/transparent</item>
<itemname="android:windowNoTitle">false</item>
<itemname="android:colorForeground">@color/blue</item>
<item name="android:colorBackground">@color/white</item>
</style>
<!-- 更改应用程序的主题,使之具有不同颜色背景且具有透明背景 -->
<style name="Theme.Translucent2">
<itemname="android:windowBackground">@color/pink</item>
<itemname="android:windowNoTitle">false</item>
<itemname="android:colorForeground">@color/green</item>
<itemname="android:colorBackground">@color/pink</item>
</style>
<!-- 更改应用程序的主题,使之具有透明背景 -->
<style name="Theme.Transparent">
<itemname="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
<itemname="android:colorForeground">@color/blue</item>
<itemname="android:colorBackground">@color/pink</item>
</style>
<style name="TextAppearance.Theme.PlainText"parent="android:TextAppearance.Theme">
<item name="android:textStyle">normal</item>
</style>
</resources>
主程序MainActivity.java代码如下:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
importandroid.widget.RadioGroup;
importandroid.widget.RadioGroup.OnCheckedChangeListener;
importandroid.widget.TextView;
public class MainActivityextends Activity {
TextView textView01;
RadioGroup radioGroup;
int[] index = new int[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView01 = (TextView)findViewById(R.id.textView01);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
for (int i = 0; i< index.length; i++) {
index[i] = radioGroup.getChildAt(i).getId();
}
radioGroup.setOnCheckedChangeListener(newOnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,int checkedId) {
if (checkedId == index[0]) {
setTheme(R.style.Theme_Transparent);
} else if(checkedId == index[1])
{
setTheme(R.style.Theme_Translucent);
} else if(checkedId == index[2])
{
setTheme(R.style.Theme_Translucent2);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action barif it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}