[教程]如何使用V7包中ActionBar(Eclipse版)
以前3.0以前的版本要使用ActionBar,必须使用国外大牛写的ActionBarSherlock这个开源项目。今年的Google/IO大会之后,Google官方在android-support-v7包中添加了ActionBar,开始让2.1以后的版本支持ActionBar,从此以后曾经最火的Android开源项目ActionBarSherlock可以退出历史舞台了。
要是用V7包中ActionBar也很简单,但有一个需要主要的地方。有些人可能刚开始仅仅是把android-support-v7-appcompat.jar导入项目中,但是在设置Activity的theme时会报错,提示找不到"@style/Theme.AppCompat"。这是由于我们要把v7和资源文件一起导入才行。
具体使用步骤(针对于Eclipse):
Create a library project based on the support library code:
appcompat
project, browse to <sdk>/extras/android/support/v7/appcompat/
.libs/
folder, right-click each .jar
file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar
andandroid-support-v7-appcompat.jar
files to the build path..jar
files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat
project requires you to export both the android-support-v4.jar
and android-support-v7-appcompat.jar
files.You now have a library project for your selected Support Library that you can use with one or more application projects.
Add the library to your application project:
appcompat
project should be listed as android-support-v7-appcompat.Once your project is set up with the support library, here's how to add the action bar:
ActionBarActivity
.Theme.AppCompat
themes for your activity. For example:<activity android:theme="@style/Theme.AppCompat.Light" ... >
Now your activity includes the action bar when running on Android 2.1 (API level 7) or higher.
On API level 11 or higher
The action bar is included in all activities that use the Theme.Holo
theme (or one of its descendants), which is the default theme when either the targetSdkVersion
or minSdkVersion
attribute is set to "11"
or higher. If you don't want the action bar for an activity, set the activity theme to Theme.Holo.NoActionBar
.
示例代码: