2013年10月3日 星期四

Android Tab View

[Android] 建立Tab View的三種方式(上)

第一種,將每個tab的內容寫在同個Activity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

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

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

            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
            </FrameLayout>
            
        </LinearLayout>
    </TabHost>

</LinearLayout>


public class MainActivity extends TabActivity implements TabContentFactory {


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

    TabHost mTabHost = getTabHost();    
        mTabHost.clearAllTabs();

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("TAB1").setContent(this));

        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("TAB2").setContent(this));
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    //getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public View createTabContent(String tag) {
    TextView textView = new TextView(this);
    textView.setText("I'm " + tag);
    return textView;

  }

}


第二種,不同tab的內容分別寫在不同的Activity
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("TAB2").setContent(this));
的setContent帶入參數intent即可!

沒有留言:

張貼留言