纯代码实现TabHost

Activity类:
package com.zzj.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;

public class Tab extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
	}
	
	private void init() {
		TabHost tabHost = new TabHost(this);
		LinearLayout linearLayout = new LinearLayout(this);
		linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
				LinearLayout.LayoutParams.MATCH_PARENT));
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.setGravity(Gravity.TOP);
		
		TabWidget tabWidget = new TabWidget(this);
		//TabHost必须有一个ID为R.id.tabs的TabWidget,内部代码是根据此ID来打出TabWidget,详看TabHost的无参setup方法
		tabWidget.setId(android.R.id.tabs);
		tabWidget.setLayoutParams(new LinearLayout.LayoutParams(-1, -2));
		
		FrameLayout frameLayout = new FrameLayout(this);
		//TabHost必须有一个ID为R.id.tabContent的FrameLayout
		frameLayout.setId(android.R.id.tabcontent);
		frameLayout.setLayoutParams(new LinearLayout.LayoutParams(-1, -2));
		Button button1 = new Button(this);
		button1.setId(123);
		button1.setText("tab button1");
		Button button2 = new Button(this);
		button2.setId(234);
		button2.setText("tab button2");
		frameLayout.addView(button1);
		frameLayout.addView(button2);
		
		linearLayout.addView(tabWidget);
		linearLayout.addView(frameLayout);
		
		tabHost.addView(linearLayout);
		//Call setup() before adding tabs if loading TabHost using findViewById().
		//You do not need to call setup() after getTabHost()
		//在添加tabs之前要调用,当然前提是TabHost不是通过getTabHost获取,也就是说不是通过TabActivity实现
		tabHost.setup();
		
		TabSpec deviceTab = tabHost.newTabSpec("Device");
		deviceTab.setIndicator( "Device Tab" );
		deviceTab.setContent(button1.getId());
		TabSpec softTab = tabHost.newTabSpec("Soft");
		softTab.setIndicator("Soft Tab");
		softTab.setContent(button2.getId());
		tabHost.addTab(deviceTab);
		tabHost.addTab(softTab);
		tabHost.setCurrentTab(0);
		
		
		setContentView(tabHost);
		
	}
}

效果:



你可能感兴趣的:(纯代码实现TabHost)