Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

android - AppCompat Action Bar library not displaying added fragments

EDIT: If I extend FragmentActivity instead of ActionBarActivity my layout shows up again (without an ActionBar of course).

The ActionBar works as intended on 4.x devices, but on my 2.3 device all I get is the ActionBar and a blank screen below it. The Fragment doesn't seem to be getting added to the Activity.

themes.xml

<style name="AppTheme" parent="AppBaseTheme">
    <item name="actionBarStyle">@style/Widget.ActionBar</item>
</style>

themes-v11.xml

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:actionBarStyle">@style/Widget.ActionBar</item>
</style>

styles.xml

<style name="Widget.ActionBar" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:background">@color/actionbar_background</item>
    <item name="background">@color/actionbar_background</item>
</style>

Activity onCreate()

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
myFragment = new WallFragment();
fragmentTransaction.add(android.R.id.content, 
    myFragment, myFragment.FRAGMENT_TAG);
fragmentTransaction.commit();

I am using Gradle to include the AppCompat ActionBar library in my app.

compile 'com.android.support:appcompat-v7:18.0.+'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Loading up the hierarchyviewer in the Android SDK's tools directory, it appears that the view you place fragments in is android.R.id.content on 4.x devices and is R.id.action_bar_activity_content on 2.3 devices running the AppCompat ActionBar library.

Unfortunately it seems that you might need to branch based off platform versions when adding fragments. This is suggested in http://code.google.com/p/android/issues/detail?id=58108 (not sure about 3.x devices yet).

Use this method to get the proper view for adding Fragment's. My testing also shows that 3.x devices act similar to 2.3 devices when using the AppCompat ActionBar library.

public static int getContentViewCompat() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ?
               android.R.id.content : R.id.action_bar_activity_content;
}


hierarchyviewer screenshots

  • 2.3

2.3

  • 4.x

4.x


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...