android fragment

 You will get all the functionality of Activity from FragmentActivity. Also you will get more options in FragmentActivity. For details please refer to click here. UsingFragmentActivity you can easily build tab and swap format. Please remember for each tab you can use different Fragment. These Fragments are reusable. So for any other FragmentActivityyou can reuse the same Fragment.

FragmentActivity 这个货具有和activity一样甚至更多的功能。使用FragmentActivity 我们可以很容易的实现tab选项卡和swap format 不知道是什么意思 估计是动画。对于tab来说 每一个tab都可以使用fragment实现。这些fragment是可以重用的 所以对于其他的FragmentActivity 都可以重用这些fragment。

Still you can use Activity for single pages like list down something and edit element of the list in next page.

我们仍然可以使用actiivty 创建单一的页面(不知道这句怎么翻译了)。

Also remember use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach aandroid.support.v4.app.Fragment to a android.app.Activity, as this will cause an exception to be thrown.

需要记住的的是 如果使用android.app.Fragment我们就直接使用activity。如果使用android.support.v4.app 我们就需要使用fragmengActivity。千万不要在activity里使用aandroid.support.v4.app.Fragment。其实就是一句话 如果是3.0以上开发 直接用activity 如果是1.6以上 3.0以下 则需要用aandroid.support.v4.app.FragmentActivity。否则会出现异常。

FragmentActivity gives you all of the functionality of Activity plus the ability to use Fragmentswhich are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.

FragmentActivity 这个货除了具有activity的一切功能外还能使用fragment。尤其是用ActionBar tab的情况下 非常好。

If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity and use the native Fragments introduced in v11 without issue. FragmentActivity was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.

如果是3.0以上开发 直接用activity 如果是1.6以上 3.0以下 则需要用Support Library

I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.

Backward Compatibility - Implementing Tabs : 地址 http://developer.android.com/training/backward-compatible-ui/abstracting.html  这个地址有教我们使用碎片实现选项卡。我会在最下边介绍。

If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future. 如果我们使用了最新的谷歌打包好的eclipse 那么用碎片实现的tab会自动创建出来。这样就轻易的将咱们的应用转化为平板的效果。

For simple single screen layouts you may still use Activity. 要是单一的屏幕布局 还是使用activity就行了。

http://mobile.tutsplus.com/tutorials/android/android-sdk_fragments/ 这个里边东西多点。1

http://mobile.tutsplus.com/tutorials/android/android-compatibility-working-with-fragments/ 2

http://developer.android.com/guide/components/fragments.html 3

 

Abstracting the New APIs

Suppose you want to use action bar tabs as the primary form of top-level navigation in your application. Unfortunately, theActionBar APIs are only available in Android 3.0 or later (API level 11+). Thus, if you want to distribute your application to devices running earlier versions of the platform, you need to provide an implementation that supports the newer API while providing a fallback mechanism that uses older APIs.

假设我们想用action bar tabs这个货 作为应用程序最上边的导航条,不幸的是ActionBar这个东西只有在3.0以上才有。所以我们需要使用功能包。

In this class, you build a tabbed user interface (UI) component that uses abstract classes with version-specific implementations to provide backward-compatibility. This lesson describes how to create an abstraction layer for the new tab APIs as the first step toward building the tab component.下边开始教我们使用怎么实现在3.0以下版本的手机上实现3.0以上的tab效果。

Prepare for Abstraction 为抽象做准备。(感觉好别扭)


Abstraction in the Java programming language involves the creation of one or more interfaces or abstract classes to hide implementation details. In the case of newer Android APIs, you can use abstraction to build version-aware components that use the current APIs on newer devices, and fallback to older, more compatible APIs on older devices.

抽象这个东西在java编程语言中涉及到了一个或者多个接口或者抽象类的创建为了隐藏具体实现细节。在安卓新版本API中 我们可以使用抽象来建立一个使用当前版本的API实现的版本识别的组件。。。。。。这句话真的不太明白 。

When using this approach, you first determine what newer classes you want to be able to use in a backward compatible way, then create abstract classes, based on the public

interfaces of the newer classes. In defining the abstraction interfaces, you should mirror the newer API as much as possible. This maximizes forward-compatibility and makes it easier to drop the abstraction layer in the future when it is no longer necessary.

当使用这种方法,你先确定你想要什么新的类能够使用在一个向后兼容的方法,然后基于新的类的公共接口创建抽象类。

After creating abstract classes for these new APIs, any number of implementations can be created and chosen at runtime. For the purposes of backward-compatibility, these implementations can vary by required API level. Thus, one implementation may use recently released APIs, while others can use older APIs.

Create an Abstract Tab Interface


In order to create a backward-compatible version of tabs, you should first determine which features and specific APIs your application requires. In the case of top-level section tabs, suppose you have the following functional requirements:

  1. Tab indicators should show text and an icon.
  2. Tabs can be associated with a fragment instance.
  3. The activity should be able to listen for tab changes.

Preparing these requirements in advance allows you to control the scope of your abstraction layer. This means that you can spend less time creating multiple implementations of your abstraction layer and begin using your new backward-compatible implementation sooner.

The key APIs for tabs are in ActionBar and ActionBar.Tab. These are the APIs to abstract in order to make your tabs version-aware. The requirements for this example project call for compatibility back to Eclair (API level 5) while taking advantage of the new tab features in Honeycomb (API Level 11). A diagram of the class structure to support these two implementations and their abstract base classes (or interfaces) is shown below.

Class diagram of abstract base classes and version-specific implementations.

Figure 1. Class diagram of abstract base classes and version-specific implementations.

Abstract ActionBar.Tab


Get started on building your tab abstraction layer by creating an abstract class representing a tab, that mirrors the ActionBar.Tab interface:

publicabstractclassCompatTab{

   
...
   
publicabstractCompatTab setText(int resId);
   
publicabstractCompatTab setIcon(int resId);
   
publicabstractCompatTab setTabListener(
           
CompatTabListener callback);
   
publicabstractCompatTab setFragment(Fragment fragment);

   
publicabstractCharSequence getText();
   
publicabstractDrawable getIcon();
   
publicabstractCompatTabListener getCallback();
   
publicabstractFragment getFragment();
   
...
}

You can use an abstract class instead of an interface here to simplify the implementation of common features such as association of tab objects with activities (not shown in the code snippet).

Abstract ActionBar Tab Methods


Next, define an abstract class that allows you to create and add tabs to an activity, like ActionBar.newTab() andActionBar.addTab():

publicabstractclassTabHelper{

   
...

   
publicCompatTab newTab(String tag){
       
// This method is implemented in a later lesson.
   
}

   
publicabstractvoid addTab(CompatTab tab);

   
...
}

In the next lessons, you create implementations for TabHelper and CompatTab that work across both older and newer platform versions.

第二课

Proxying to the New APIs

This lesson shows you how to subclass the CompatTab andTabHelper abstract classes and use new APIs. Your application can use this implementation on devices running a platform version that supports them.

Implement Tabs Using New APIs


The concrete classes for CompatTab and TabHelper that use newer APIs are a proxy implementation. Since the abstract classes defined in the previous lesson mirror the new APIs (class structure, method signatures, etc.), the concrete classes that use these newer APIs simply proxy method calls and their results.

You can directly use newer APIs in these concrete classes—and not crash on earlier devices—because of lazy class loading. Classes are loaded and initialized on first access—instantiating the class or accessing one of its static fields or methods for the first time. Thus, as long as you don't instantiate the Honeycomb-specific implementations on pre-Honeycomb devices, the Dalvik VM won't throw any VerifyError exceptions.

A good naming convention for this implementation is to append the API level or platform version code name corresponding to the APIs required by the concrete classes. For example, the native tab implementation can be provided by CompatTabHoneycomb and TabHelperHoneycomb classes, since they rely on APIs available in Android 3.0 (API level 11) or later.

Class diagram for the Honeycomb implementation of tabs.

Figure 1. Class diagram for the Honeycomb implementation of tabs.

Implement CompatTabHoneycomb


CompatTabHoneycomb is the implementation of the CompatTab abstract class that TabHelperHoneycombuses to reference individual tabs. CompatTabHoneycomb simply proxies all method calls to its contained ActionBar.Tab object.

Begin implementing CompatTabHoneycomb using the new ActionBar.Tab APIs:

public class CompatTabHoneycomb extends CompatTab {
    // The native tab object that this CompatTab acts as a proxy for.
    ActionBar.Tab mTab;
    ...

    protected CompatTabHoneycomb(FragmentActivity activity, String tag) {
        ...
        // Proxy to new ActionBar.newTab API
        mTab = activity.getActionBar().newTab();
    }

    public CompatTab setText(int resId) {
        // Proxy to new ActionBar.Tab.setText API
        mTab.setText(resId);
        return this;
    }

    ...
    // Do the same for other properties (icon, callback, etc.)
}

Implement TabHelperHoneycomb


TabHelperHoneycomb is the implementation of the TabHelper abstract class that proxies method calls to an actual ActionBar, obtained from its contained Activity.

Implement TabHelperHoneycomb, proxying method calls to the ActionBar API:

public class TabHelperHoneycomb extends TabHelper {
    ActionBar mActionBar;
    ...

    protected void setUp() {
        if (mActionBar == null) {
            mActionBar = mActivity.getActionBar();
            mActionBar.setNavigationMode(
                    ActionBar.NAVIGATION_MODE_TABS);
        }
    }

    public void addTab(CompatTab tab) {
        ...
        // Tab is a CompatTabHoneycomb instance, so its
        // native tab object is an ActionBar.Tab.
        mActionBar.addTab((ActionBar.Tab) tab.getTab());
    }

    // The other important method, newTab() is part of
    // the base implementation.
}
第三课

Creating an Implementation with Older APIs

THIS LESSON TEACHES YOU TO:

  1. Decide on a Substitute Solution
  2. Implement Tabs Using Older APIs

TRY IT OUT

This lesson discusses how to create an implementation that mirrors newer APIs yet supports older devices.

Decide on a Substitute Solution


The most challenging task in using newer UI features in a backward-compatible way is deciding on and implementing an older (fallback) solution for older platform versions. In many cases, it's possible to fulfill the purpose of these newer UI components using older UI framework features. For example:

  • Action bars can be implemented using a horizontal LinearLayout containing image buttons, either as custom title bars or as views in your activity layout. Overflow actions can be presented under the device Menu button.

  • Action bar tabs can be implemented using a horizontal LinearLayout containing buttons, or using the TabWidget UI element.

  • NumberPicker and Switch widgets can be implemented using Spinner and ToggleButton widgets, respectively.

  • ListPopupWindow and PopupMenu widgets can be implemented using PopupWindow widgets.

There generally isn't a one-size-fits-all solution for backporting newer UI components to older devices. Be mindful of the user experience: on older devices, users may not be familiar with newer design patterns and UI components. Give some thought as to how the same functionality can be delivered using familiar elements. In many cases this is less of a concern—if newer UI components are prominent in the application ecosystem (such as the action bar), or where the interaction model is extremely simple and intuitive (such as swipe views using a ViewPager).

Implement Tabs Using Older APIs


To create an older implementation of action bar tabs, you can use a TabWidget and TabHost (although one can alternatively use horizontally laid-out Button widgets). Implement this in classes calledTabHelperEclair and CompatTabEclair, since this implementation uses APIs introduced no later than Android 2.0 (Eclair).

Class diagram for the Eclair implementation of tabs.

Figure 1. Class diagram for the Eclair implementation of tabs.

The CompatTabEclair implementation stores tab properties such as the tab text and icon in instance variables, since there isn't an ActionBar.Tab object available to handle this storage:

public class CompatTabEclair extends CompatTab {
    // Store these properties in the instance,
    // as there is no ActionBar.Tab object.
    private CharSequence mText;
    ...

    public CompatTab setText(int resId) {
        // Our older implementation simply stores this
        // information in the object instance.
        mText = mActivity.getResources().getText(resId);
        return this;
    }

    ...
    // Do the same for other properties (icon, callback, etc.)
}

The TabHelperEclair implementation makes use of methods on the TabHost widget for creatingTabHost.TabSpec objects and tab indicators:

public class TabHelperEclair extends TabHelper {
    private TabHost mTabHost;
    ...

    protected void setUp() {
        if (mTabHost == null) {
            // Our activity layout for pre-Honeycomb devices
            // must contain a TabHost.
            mTabHost = (TabHost) mActivity.findViewById(
                    android.R.id.tabhost);
            mTabHost.setup();
        }
    }

    public void addTab(CompatTab tab) {
        ...
        TabSpec spec = mTabHost
                .newTabSpec(tag)
                .setIndicator(tab.getText()); // And optional icon
        ...
        mTabHost.addTab(spec);
    }

    // The other important method, newTab() is part of
    // the base implementation.
}

You now have two implementations of CompatTab and TabHelper: one that works on devices running Android 3.0 or later and uses new APIs, and another that works on devices running Android 2.0 or later and uses older APIs. The next lesson discusses using these implementations in your application.

第四课

Using the Version-Aware Component

Now that you have two implementations of TabHelper andCompatTab—one for Android 3.0 and later and one for earlier versions of the platform—it's time to do something with these implementations. This lesson discusses creating the logic for switching between these implementations, creating version-aware layouts, and finally using the backward-compatible UI component.

Add the Switching Logic


The TabHelper abstract class acts as a factory for creating version-appropriate TabHelper and CompatTab instances, based on the current device's platform version:

public abstract class TabHelper {
    ...
    // Usage is TabHelper.createInstance(activity)
    public static TabHelper createInstance(FragmentActivity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            return new TabHelperHoneycomb(activity);
        } else {
            return new TabHelperEclair(activity);
        }
    }

    // Usage is mTabHelper.newTab("tag")
    public CompatTab newTab(String tag) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            return new CompatTabHoneycomb(mActivity, tag);
        } else {
            return new CompatTabEclair(mActivity, tag);
        }
    }
    ...
}

Create a Version-Aware Activity Layout


The next step is to provide layouts for your activity that can support the two tab implementations. For the older implementation (TabHelperEclair), you need to ensure that your activity layout contains a TabWidget andTabHost, along with a container for tab contents:

res/layout/main.xml:

<!-- This layout is for API level 5-10 only. -->
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

    </LinearLayout>
</TabHost>

For the TabHelperHoneycomb implementation, all you need is a FrameLayout to contain the tab contents, since the tab indicators are provided by the ActionBar:

res/layout-v11/main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabcontent"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

At runtime, Android will decide which version of the main.xml layout to inflate depending on the platform version. This is the same logic shown in the previous section to determine which TabHelper implementation to use.

Use TabHelper in Your Activity


In your activity's onCreate() method, you can obtain a TabHelper object and add tabs with the following code:

@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);

    TabHelper tabHelper = TabHelper.createInstance(this);
    tabHelper.setUp();

    CompatTab photosTab = tabHelper
            .newTab("photos")
            .setText(R.string.tab_photos);
    tabHelper.addTab(photosTab);

    CompatTab videosTab = tabHelper
            .newTab("videos")
            .setText(R.string.tab_videos);
    tabHelper.addTab(videosTab);
}

When running the application, this code inflates the correct activity layout and instantiates either aTabHelperHoneycomb or TabHelperEclair object. The concrete class that's actually used is opaque to the activity, since they share the common TabHelper interface.

Below are two screenshots of this implementation running on an Android 2.3 and Android 4.0 device.

Example screenshot of tabs running on an Android 2.3 device (using TabHelperEclair). Example screenshots of tabs running on an Android 4.0 device (using TabHelperHoneycomb).

Figure 1. Example screenshots of backward-compatible tabs running on an Android 2.3 device (using TabHelperEclair) and an Android 4.0 device (using TabHelperHoneycomb).

大概就是上边的几步 我们就可以根据最新的API来构建出向后兼容的实现来创建出新版本UI效果运行在低版本API手机上。顶谷歌 真的在教我们东西 教我们思想。

 

 

 

posted @ 2013-04-05 16:21  ITeer  阅读(673)  评论(0编辑  收藏  举报