2016-06-28 32 views
3

我有一个应用程序,我迫切需要从使用旧的ActivityGroup类转换为Fragments。但我不确定如何去解决它。以下是我现在使用的代码示例。任何人都可以提供一些见解,我应该采取哪些步骤来开始将其切换到使用Fragments/FragmentManager?将ActivityGroup应用转换为使用Fragments/FragmentGroup

Main.java

public class Main extends TabActivity implements OnTabChangeListener { 

    public static TextView txtViewHeading; 
    public static Button btnBack; 
    public static ImageButton btnShare; 
    public static Main mainActivity; 
    public static Boolean isVisible = false; 
    private GoogleCloudMessaging gcm; 
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; 

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

     mainActivity = this; 
     NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, PushHandler.class); 
     registerWithNotificationHubs(); 

     //reference headings text & button for access from child activities 
     txtViewHeading = (TextView) findViewById(R.id.txtViewHeading); 
     btnBack = (Button) findViewById(R.id.btnBack); 
     btnShare = (ImageButton) findViewById(R.id.btnShare); 

     // Update the font for the heading and back button 
     Typeface arialTypeface = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/arial.ttf"); 
     Typeface myriadTypeface = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/myriad.ttf"); 
     txtViewHeading.setTypeface(myriadTypeface); 
     btnBack.setTypeface(arialTypeface); 

     Resources res = getResources(); 
     TabHost tabsNavigation = getTabHost(); 

     // Set up the views for each tab - custom view used for Badge icon 
     LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     // Set up my tabs...each one looks similar to this 
     View statusTabView = inflater.inflate(R.layout.tab, null); 
     ImageView statusTabIcon = (ImageView) statusTabView.findViewById(R.id.tabIcon); 
     statusTabIcon.setImageResource(R.drawable.tab_first); 
     TextView statusTabText = (TextView) statusTabView.findViewById(R.id.tabText); 
     statusTabText.setText("Status"); 
     statusTabText.setTypeface(arialTypeface); 
     statusTabBadge = (TextView) statusTabView.findViewById(R.id.tabBadge); 
     statusTabBadge.setTypeface(arialTypeface); 
     tabsNavigation.addTab(tabsNavigation.newTabSpec(getResources().getString(R.string.main_tab_status)) 
       .setIndicator(statusTabView) 
       .setContent(new Intent(this, StatusGroupActivity.class) 
       .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))); 

     //Set default tab to Status 
     tabsNavigation.setCurrentTab(0); 
     tabsNavigation.setOnTabChangedListener(this); 

    } 


    /* Set txtViewHeading text to selected tab text */ 
    @Override 
    public void onTabChanged(String tabId) { 
     // TODO Auto-generated method stub 
     txtViewHeading.setText(tabId); 
    } 

    /* Set code to execute when onDestroy method is called */ 
    @Override 
    protected void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
    } 


    /* Set code to execute when onPause method is called */ 
    @Override 
    protected void onPause() { 
     super.onPause(); 
     isVisible = false; 
    } 

    /* Set code to execute when onResume method is called */ 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     isVisible = true; 
    } 


    /* Set code to execute when onStop method is called */ 
    @Override 
    protected void onStop() { 
     super.onStop(); 
     isVisible = false; 
    } 

    /** 
    * Check the device to make sure it has the Google Play Services APK. If 
    * it doesn't, display a dialog that allows users to download the APK from 
    * the Google Play Store or enable it in the device's system settings. 
    */ 
    private boolean checkPlayServices() { 
     GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); 
     int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (apiAvailability.isUserResolvableError(resultCode)) { 
       apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) 
         .show(); 
      } else { 
       ToastNotify("This device is not supported by Google Play Services."); 
       finish(); 
      } 
      return false; 
     } 

     return true; 
    } 

    public void ToastNotify(final String notificationMessage) { 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       Toast.makeText(Main.this, notificationMessage, Toast.LENGTH_LONG).show(); 
      } 
     }); 
    } 

    public void registerWithNotificationHubs() 
    { 
     if (checkPlayServices()) { 
      // Start IntentService to register this application with GCM. 
      Intent intent = new Intent(this, RegistrationIntentService.class); 
      startService(intent); 
     } 
    } 

} 

TabGroupActivity.java

public class TabGroupActivity extends ActivityGroup 
{ 
    private ArrayList<String> mIdList; 
    Button btnBack; 
    ImageButton btnShare; 
    TextView txtViewHeading; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     btnBack = Main.btnBack; 
     btnShare = Main.btnShare; 
     txtViewHeading = Main.txtViewHeading; 
     btnBack.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       onBackPressed(); 
      } 
     }); 
     if (mIdList == null) mIdList = new ArrayList<String>(); 
    } 
    /** 
    * This is called when a child activity of this one calls its finish method. 
    * This implementation calls {@link LocalActivityManager#destroyActivity} on the child activity 
    * and starts the previous activity. 
    * If the last child activity just called finish(),this activity (the parent), 
    * calls finish to finish the entire group. 
    */ 
    @Override 
    public void finishFromChild(Activity child) 
    { 
     try 
     { 
      btnShare.setVisibility(View.GONE); 
      LocalActivityManager manager = getLocalActivityManager(); 
      int index = mIdList.size()-1; 

      if (index < 1) 
      { 
       finish(); 
       return; 
      } 

      manager.destroyActivity(mIdList.get(index), true); 
      mIdList.remove(index); 
      index--; 
      String lastId = mIdList.get(index); 
      Intent lastIntent = manager.getActivity(lastId).getIntent(); 
      Window newWindow = manager.startActivity(lastId, lastIntent);   
      setContentView(newWindow.getDecorView()); 
      //Set Heading text to current Id 
      txtViewHeading.setText(getActivityHeading(lastId));  
      //Set Back button text to previous Id if applicable 
      btnBack.setVisibility(View.VISIBLE);     
      //Back button 
      String backId = ""; 
      if(mIdList.size() > 1) 
      { 
       backId = mIdList.get(mIdList.size()-2); 
       btnBack.setVisibility(View.VISIBLE); 
       btnBack.setText(getActivityHeading(backId)); 
       txtViewHeading.setPadding(10,0,0,0); 
      } 
      else 
      { 
       btnBack.setVisibility(View.GONE); 
       txtViewHeading.setPadding(0,0,0,0); 
      } 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Starts an Activity as a child Activity to this. 
    * @param Id Unique identifier of the activity to be started. 
    * @param intent The Intent describing the activity to be started. 
    */ 
    public void startChildActivity(String Id, Intent intent) 
    { 
     try 
     { 
      btnShare.setVisibility(View.GONE); 
      Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); 
      if (window != null) 
      { 
       mIdList.add(Id); 
       setContentView(window.getDecorView()); 
       txtViewHeading.setText(getActivityHeading(Id)); 
       //Back button 
       String backId = ""; 
       if(mIdList.size() > 1) 
       { 
        backId = mIdList.get(mIdList.size()-2); 
        btnBack.setVisibility(View.VISIBLE); 
        btnBack.setText(backId); 
        txtViewHeading.setPadding(5,0,0,0); 
       } 
       else 
       { 
        btnBack.setVisibility(View.GONE); 
        txtViewHeading.setPadding(0,0,0,0); 
       }     
      } 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * The primary purpose is to prevent systems before android.os.Build.VERSION_CODES.ECLAIR 
    * from calling their default KeyEvent.KEYCODE_BACK during onKeyDown. 
    */ 
    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    { 
     if (keyCode == KeyEvent.KEYCODE_BACK) 
     { 
      //preventing default 
      return true; 
     } 
     return super.onKeyDown(keyCode, event); 
    } 

    /** 
    * Overrides the default implementation for KeyEvent.KEYCODE_BACK 
    * so that all systems call onBackPressed(). 
    */ 
    @Override 
    public boolean onKeyUp(int keyCode, KeyEvent event) 
    { 
     if (keyCode == KeyEvent.KEYCODE_BACK) 
     { 
      onBackPressed(); 
      return true; 
     } 
     return super.onKeyUp(keyCode, event); 
    } 

    /** 
    * If a Child Activity handles KeyEvent.KEYCODE_BACK. 
    * Simply override and add this method. 
    */ 
    @Override 
    public void onBackPressed() 
    { 
     try 
     { 
      btnShare.setVisibility(View.GONE); 
      int length = mIdList.size(); 
      if (length > 1) 
      { 
       Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1)); 
       current.finish(); 
      } 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Get the correct heading text and language based on activity id 
    */ 
    public String getActivityHeading(String id) 
    { 
     // method that returns the TEXT for my main heading TextView based on the activity we're on...   
    }    

} 

StatusGroupActivity

public class StatusGroupActivity extends TabGroupActivity 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     startChildActivity("Status", new Intent(this,Status.class)); 
    }  

} 

...所以B asically当我的应用程序加载时,我得到我的标签在底部,我的头在顶部,并在中间的“标签内容”。在我的状态活动中,我可以从中加载另一个活动...

Intent intent = new Intent(getParent(), SomeOtherActivity.class) 
TabGroupActivity parentActivity = (TabGroupActivity)getParent(); 
parentActivity.startChildActivity("Some Other Activity", intent); 

...并将SomeOtherActivity活动加载到内容区域。点击返回到状态屏幕。

任何指针,示例和协助将此转换为使用Fragments非常感谢。我会很乐意捐出我的代表500。点一个完整的例子。

main.xml中(主要活动版式文件)

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@android:id/tabhost" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:animateLayoutChanges="true" 
    tools:ignore="ContentDescription,HardcodedText" > 

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

     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 

      <ImageView 
       android:id="@+id/imageSuccess" 
       android:layout_width="wrap_content" 
       android:layout_height="40dp" 
       android:adjustViewBounds="true" 
       android:scaleType="matrix" 
       android:src="@drawable/bg_navbar_blank" /> 

      <com.myproject.android.BgButtonStyle 
       android:id="@+id/btnBack" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginLeft="5dp" 
       android:layout_marginTop="0dp" 
       android:background="@drawable/back_button" 
       android:text="" 
       android:textColor="@color/White" 
       android:textSize="12sp" 
       android:visibility="visible" 
       android:layout_alignParentLeft="true" 
       android:layout_centerVertical="true" 
       android:padding="5dp"/> 

      <ImageButton 
       android:id="@+id/btnShare" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentRight="true" 
       android:layout_centerVertical="true" 
       android:layout_marginRight="15dp" 
       android:background="@null" 
       android:src="@drawable/icon_share" 
       android:visibility="visible" 
       android:adjustViewBounds="false" 
       android:scaleType="fitXY"/> 

      <com.myproject.android.AutoResizeTextView 
       android:id="@+id/txtViewHeading" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:gravity="center_horizontal" 
       android:paddingLeft="5dp" 
       android:text="Status" 
       android:textAppearance="?android:attr/textAppearanceLarge" 
       android:textSize="28sp" 
       android:textStyle="bold" 
       android:paddingRight="5dp" 
       android:layout_toEndOf="@id/btnBack" 
       android:layout_toStartOf="@id/btnShare" 
       android:layout_centerVertical="true" 
       android:lines="1"/> 

     </RelativeLayout> 

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

     <TabWidget 
      android:id="@android:id/tabs" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginBottom="-4dp" 
      android:layout_weight="0" 
      android:background="@drawable/bg_tabs"> 

     </TabWidget> 
    </LinearLayout> 

</android.support.v4.app.FragmentTabHost> 

在我目前的TabGroupActivity类,在finishFromChild和startChildActivity方法,我可以在我的主要活动来调用的setText txtViewHeading TextView元素上布局。目前的活动是什么“标题”。如果组中有多个活动,则后退按钮显示前一个标题。我如何在下面的例子中复制它?主要的活动布局与我的不同。

+0

访问[this](http://portabledroid.wordpress.com/2011/04/19/programmatic-and-layout-fragments/)。希望这将有助于:) –

+0

谁投下了我的问题,你能解释你这样做的理由吗? – Phil

+0

我也想知道! –

回答

1

首先,你需要添加Design Support LibraryAppCompatLibrary到您的项目

这段代码添加到您的应用程序gradle这个

compile 'com.android.support:appcompat-v7:24.0.0' 
compile 'com.android.support:design:24.0.0' 

布局activity_main.xml(如main.xml中在你的代码)

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/main_content" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:fitsSystemWindows="true"> 

<android.support.design.widget.AppBarLayout 
    android:id="@+id/appbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:paddingTop="@dimen/appbar_padding_top" 
    android:theme="@style/AppTheme.AppBarOverlay"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" 
     app:layout_scrollFlags="scroll|enterAlways" 
     app:popupTheme="@style/AppTheme.PopupOverlay"> 

    </android.support.v7.widget.Toolbar> 

    <android.support.design.widget.TabLayout 
     android:id="@+id/tabs" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

</android.support.design.widget.AppBarLayout> 

<android.support.v4.view.ViewPager 
    android:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" /> 

</android.support.design.widget.CoordinatorLayout> 

在上述布局ViewPager将提供水平布局来显示选项卡。您可以使用选项卡在单个屏幕中显示更多屏幕。您可以尽可能快地滑动标签。

根片段

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

信息查看第一块碎片

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:background="#ff0" 
android:layout_height="match_parent" > 

<TextView 
    android:id="@+id/tv" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center_horizontal" 
    android:text="@string/first_fragment" /> 
<Button 
    android:id="@+id/btn" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:layout_width="wrap_content" 
    android:text="@string/to_second_fragment"/> 

</RelativeLayout> 

信息查看第二和个人(一个或多个)片段

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin"> 

<TextView 
    android:id="@+id/section_label" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

</RelativeLayout> 

现在添加MainActivity(如主要活动在你的代码)下,所有这件事情会处理。

public class MainActivity extends AppCompatActivity { 

private TabGroupAdapter mTabGroupAdapter; 
private ViewPager mViewPager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); 
    fragmentList.add(new RootFragment()); 
    fragmentList.add(new IndividualFragment1()); 
    fragmentList.add(new IndividualFragment2()); 
    ArrayList<String> name = new ArrayList<String>() { 
     { 
      add("Root Tab"); 
      add("Second Tab"); 
      add("Third Tab"); 
     } 
    }; 
    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mTabGroupAdapter = new TabGroupAdapter(getSupportFragmentManager(),name, fragmentList,); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.container); 
    mViewPager.setAdapter(mTabGroupAdapter); 

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
    tabLayout.setupWithViewPager(mViewPager); 

} 
} 

有一个FragmentPagerAdapter定义为mTabGroupAdapter内部MainActivity,将添加一个布局内的不同的选项卡。

首先我们将mTabGroupAdapter绑定到mViewPager

TabLayout将起到TabHost的作用,其下的Tab将被添加FragmentPagerAdapter

mViewPager绑定到Tablayout

MainActivity TabLayout将显示选项卡的名称。

TabGroupAdapter

public class TabGroupAdapter extends FragmentPagerAdapter { 

    private ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); 
    private ArrayList<String> fragment_name; 

    public TabGroupAdapter(FragmentManager fm, ArrayList<String> name, ArrayList<Fragment> list) { 
     super(fm); 
     this.fragmentList = list; 
     this.fragment_name = name; 
    } 

    @Override 
    public Fragment getItem(int position) { 
     return fragmentList.get(position); 
    } 

    @Override 
    public int getCount() { 
     return fragmentList.size(); 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     return fragment_name.get(position); 
    } 
} 

TabGroupAdapter你会传递一个List of fragments(or single fragment)list of fragments name(or single name)在构造函数的参数。

IndividualFragment(s)将表现为单独的Tab而不是Activity。

RootFragment将充当用于其它片段(第一片段与第二片段)

根片段的容器

public class RootFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.root_fragment, container, false); 
     FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
     fragmentTransaction.replace(R.id.root_frame, new FirstFragment()); 
     fragmentTransaction.commit(); 
     return view; 
    } 
} 

第一块碎片

public class FirstFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.first_fragment, container, false); 

     Button btn = (Button) view.findViewById(R.id.btn); 

     btn.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
      //use the "root frame" defined in 
      //"root_fragment.xml" as the reference to replace fragment 

      fragmentTransaction.replace(R.id.root_frame, new SecondFragment()); 
      /* 
      * allow to add the fragment 
      * to the stack and return to it later, by pressing back 
      */ 
      fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
      fragmentTransaction.addToBackStack(null); 
      fragmentTransaction.commit(); 
     } 
    }); 
    } 
} 

第二块碎片

public class SecondFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     return rootView; 
    } 
} 

个人(S)片段

public class IndividualFragment1 extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     return rootView; 
    } 
} 



public class IndividualFragment2 extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     return rootView; 
    } 
} 

OnCreateView方法,你能设置一个Tab的布局。

您不必使用getTabHost()方法。

让我知道你是否坚持任何问题。

每当你想在查看传呼机动态更改或更新选项卡只需添加或从fragmentList删除项,调用此方法mTabGroupAdapter.notifyDataSetChanged();MainActivity

+0

在你的例子中,在我的例子中,替换TabGroupActivity会是什么? – Phil

+0

所以你想开始一个新的Activity或newFragment。 –

+0

我想开始一个新的片段。我宁愿坚持使用活动,但ActivityGroup已被弃用,因此我正转向片段。我需要能够执行与我的TabGroupActivity类提供的相同操作(或类似) – Phil

1

这些依赖添加到您的项目:

compile 'com.android.support:appcompat-v7:23.4.0' 
compile 'com.android.support:design:23.4.0' 

首先改变你的Main活动必须从AppCompatActivity延长。

不是改变你的主活动的布局如下图所示:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/coordinatorlayout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context=".Main"> 

    <android.support.design.widget.AppBarLayout 
     android:id="@+id/appbarlayout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

     <include 
      layout="@layout/toolbar_default" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      app:layout_scrollFlags="scroll|enterAlways" /> 

     <android.support.design.widget.TabLayout 
      android:id="@+id/tabs" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      app:tabGravity="fill" 
      app:tabMaxWidth="0dp" 
      app:tabIndicatorHeight="4dp" 
      app:tabMode="fixed" 
      app:tabIndicatorColor="@android:color/white" 
      android:background="@color/AppPrimary"/> 
    </android.support.design.widget.AppBarLayout> 

    <?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context=".dashboard.DashboardActivity" 
    tools:showIn="@layout/activity_dashboard"> 


    <android.support.v4.view.ViewPager 
     android:id="@+id/viewpager_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 

</RelativeLayout> 

</android.support.design.widget.CoordinatorLayout> 

而且这里有一个工具栏布局的例子。你可以自定义你想要的。

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.Toolbar 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/toolbar_main" 
    style="@style/Widget.MyApp.Toolbar.Solid" 
    android:layout_width="match_parent" 
    android:layout_height="@dimen/abc_action_bar_default_height_material" 
    android:background="@color/AppPrimary" 
    app:contentInsetEnd="16dp" 
    app:contentInsetStart="16dp" /> 

比你需要创建的片段,你将在你的选项卡中使用,而不是你用于选项卡的活动。在这种情况下,这将是你的Status Activity,如果我没有错。

定义StatusFragment象下面这样:

public class StatusFragment extends Fragment 
{ 
    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 
     // this is your Status fragment. You can do stuff which you did in  Status activity 
    } 
} 

比你需要定义你与你的标签绑定和你TabHost转换成片段/片段经理类型选项卡适配器。标题字符串数组包含您将在选项卡指示器中显示的字符串。如“状态,我的假设标签,我真棒标签2

public class DashboardTabsAdapter extends FragmentPagerAdapter { 
    private String[] mTitles; 

    public DashboardTabsAdapter(FragmentManager fm, String[] titles) { 
     super(fm); 
     this.mTitles = titles; 
    } 

    @Override 
    public Fragment getItem(int position) { 
     return new StatusFragment(); 
     // You can define some other fragments if you want to do different types of operations in your tabs and switch this position and return that kind of fragment. 
    } 

    @Override 
    public int getCount() { 
     return mTitles.length; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     return mTitles[position]; 
    } 
} 

最后,在你的主要活动找到自己的看法寻呼机,标签创建一个新的适配器,并将它们绑定

 final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
     final DashboardTabsAdapter dashboardTabsAdapter = new DashboardTabsAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.tab_titles)); 
     mViewPagerMain = (ViewPager) findViewById(R.id.viewpager_main); 
     mViewPagerMain.setOffscreenPageLimit(3); 
     mViewPagerMain.setAdapter(dashboardTabsAdapter); 
     tabLayout.setupWithViewPager(mViewPagerMain); 

编辑:您你不再需要TabHostTabActivity你的标签页面活动将是你的ViewPager,它处理屏幕变化和片段的生命周期。如果你需要从片段中获得这个活动,你可以使用getActivity()方法并将它投射到你的活动中,使用它的公共方法。

+0

谁投下了这个职位,你能否提供一个原因?我开始实施它。它不正确吗? – Phil

+0

当我将扩展TabActivity的主要活动切换到AppCompatActivity时,我无法再调用getTabHost();它说,无法解析方法.. – Phil

+0

此外,你的新的主要活动布局有多个<?xml version =“1.0”encoding =“utf-8”?>声明,以及“tools:showIn =”@ layout/activity_dashboard“表示无法解析符号 – Phil