Android如何使用样式创建半透明窗体
本示例介绍如何使用Android系统样式和自定义样式创建半透明界面。
1. 定义清单文件(AndroidManifest.xml)
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="my.andriod.test"
android:versionCode="1"
android:versionName="1.0">
<applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
<!-- 使用自定义半透明主题样式 android:theme="@style/Theme.Translucent" -->
<activityandroid:name=".TranslucentActivity"
android:label="@string/app_name"
android:theme="@style/Theme.Translucent">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- 使用Android系统半透明主题样式
<activity android:name=".TranslucentActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
-->
</application>
<uses-sdkandroid:minSdkVersion="9"/>
</manifest>
2. 定义字符串资源(strings.xml)
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<stringname="hello">Hello World, TranslucentActivity!</string>
<stringname="app_name">TranslucentActivity</string>
<stringname="activity_translucent">App/Activity/Translucent</string>
<stringname="translucent_background">Example of how you can make an
activity have a translucent background, compositingover
whatever is behind it.</string>
</resources>
3. 定义自定义样式(values/styles.xml)
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<!-- 继承Android系统的半透明主题样式,并指定半透明背景的颜色、隐藏窗口标题和前景色 -->
<stylename="Theme.Translucent"parent="android:style/Theme.Translucent">
<itemname="android:windowBackground">@drawable/translucent_background</item>
<itemname="android:windowNoTitle">true</item>
<itemname="android:colorForeground">#fff</item>
</style>
</resources>
4. 定义半透明颜色(colors.xml)
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<drawablename="translucent_background">#e0000000</drawable>
</resources>
5. 定义布局文件(translucent_background.xml)
<?xmlversion="1.0"encoding="utf-8"?>
<!-- 在Activity中显示文本-->
<TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/text"
android:layout_width="match_parent"android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/translucent_background"/>
6. 创建Activity(TranslucentActivity.java)
packagemy.andriod.test;
importandroid.app.Activity;
importandroid.os.Bundle;
publicclassTranslucentActivity extendsActivity {
/** Activity首次创建时,调用这个方法*/
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//填充布局
setContentView(R.layout.translucent_background);
}
}