您的位置:首页 > 移动开发

使用appcompat_v7,定义activity全屏或无标题栏

2016-04-21 16:21 459 查看
我刚开始使用Google新推出的appcompat_v7的时候,发现当项目引用这个兼容项目并且Activity继承ActionBarActivity后,就必须使用Theme.Appcompat系列的Style才行,不然程序运行会报错的。

换个主题好说,于是把程序的Style换了,程序运行就不报错了。但是问题又来了,我要Activity不显示标题栏,但是Theme.Appcompat系列的主题中就没有NoTitleBar之类的,那怎么设置主题呢?

我试着自己在Styles.xml文件中自己写了一个MyAppTheme,如下:

[html] view
plain copy

<!--

Base application theme, dependent on API level. This theme is replaced

by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

-->

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">

<!--

Theme customizations available in newer API levels can go in

res/values-vXX/styles.xml, while customizations related to

backward-compatibility can go here.

-->

</style>

<!-- Application theme. -->

<style name="AppTheme" parent="AppBaseTheme">

<!-- All customizations that are NOT specific to a particular API-level can go here. -->

</style>

<!-- Activity无标题栏 开始-->

<style name="MyAppTheme" parent="AppTheme">

<item name="android:windowNoTitle">true</item>

</style>

<!-- Activity无标题栏 结束-->

(注意AppBaseTheme我改成了Theme.AppCompat.Light,并且要把values-v11和values-v14文件夹中的styles.xml里的AppBaseTheme也一起修改掉)。

修改后,在AndroidManifest.xml文件中,把application节点的Android:theme属性设置为“@style/MyAppTheme”。

然后在我的手机上运行起来,OK,没有问题,确实标题栏没有了,达到了我想要的效果。

不过还没完,我又把我的两个安卓虚拟机跑起来,系统版本分别是4.4.2和2.3.3,放到虚拟机上测试。4.4.2的虚拟机没问题,显示效果跟真机一样,但是2.3.3就没用了,还是有标题栏存在……奇怪

后来又试了半天无果,跑到stackoverflow上面查了一下,终于有收获了。发现应该是2.x的系统下style还需要windowActionBar的属性设置为false才行,修改后的MyAppTheme如下:

[html] view
plain copy

<!-- Activity无标题栏 开始-->

<style name="MyAppTheme" parent="AppTheme">

<item name="android:windowNoTitle">true</item>

<item name="windowActionBar">false</item>

</style>

<!-- Activity无标题栏 结束-->

再用2.3.3的虚拟机测试,OK,不会显示标题栏了,并且4.x的虚拟机上也没有问题。

注意要添加一个代码在自己xml布局的根节点中加入:

android:fitsSystemWindows="true"
android:clipToPadding="true"

不然会出现:



自己的布局被通知栏给覆盖了。

-----------------------------------------------------------------------------------

如果还需要全屏的效果,再给style中加上如下的两个属性就行了:

[html] view
plain copy

<item name="android:windowFullscreen">true</item>

<item name="android:windowContentOverlay">@null</item>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: