liguofeng29’s blog

個人勉強用ブログだっす。

AndroidのIntent - Intentを使用してTabページを作成する

Tabページを追加する際のTabHost.TabSpectのメソッド

  1. setContect(int viewId) - id指定のViewをTabページにする
  2. setContent(Intent intent) - Intentに対応するActivityをTabページにする

サンプルコード TabActivity1,TabActivity2,TabActivity3と対応するlayoutは省略する。

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:layout_weight="1">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <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="match_parent">
        </FrameLayout>
    </LinearLayout>
</TabHost>
package com.example.liguofeng.tabhost;

import android.app.TabActivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TabHost;

public class MainActivity extends TabActivity {

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

        TabHost tabhost = getTabHost();

        // IntentでTabページ追加
        tabhost.addTab(tabhost
                .newTabSpec("tab1")
                .setIndicator("TAB1", getResources().getDrawable(R.drawable.ic_launcher))
                .setContent(new Intent(this, TabActivity1.class)
                ));

        // IntentでTabページ追加
        tabhost.addTab(tabhost
                .newTabSpec("tab2")
                .setIndicator("TAB2")
                .setContent(new Intent(this, TabActivity2.class)
                ));

        // IntentでTabページ追加
        tabhost.addTab(tabhost
                .newTabSpec("tab3")
                .setIndicator("TAB3")
                .setContent(new Intent(this, TabActivity3.class)
                ));
    }
}

f:id:liguofeng29:20151212005614g:plain