需求:
本来TabHost已经被遗弃了,但是Android4.2上ActionBar不给力,tab不能调节高度,宽度调整也有限制,有时候还是得使用TabHost
示例:
src/com.example.hellotabhost.HelloTabHost.java
package com.example.hellotabhost;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.TabActivity;
import android.content.Intent;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
@SuppressLint("NewApi")
public class HelloTabHost extends TabActivity {
private static final String TAG = "HelloTabHost";
private TabHost mtabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mtabHost = getTabHost();
mtabHost.addTab(mtabHost.newTabSpec("tab1")
.setIndicator(getString(R.string.tabs_1_tab_1), getResources().getDrawable(R.drawable.ic_launcher))
.setContent(new Intent(this, A_Activity.class)));
mtabHost.addTab(mtabHost.newTabSpec("tab2")
.setIndicator(getString(R.string.tabs_1_tab_2),getResources().getDrawable(R.drawable.ic_launcher))
.setContent(new Intent(this, B_Activity.class)));
//
final TabWidget tabWidget = mtabHost.getTabWidget();
for (int i = 0; i < tabWidget.getChildCount(); i++) {
tabWidget.getChildAt(i).getLayoutParams().height = 120; //设置Tab高度
tabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg); //设置Tab项背景色
//设置Tab的字体的大小和颜色
TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);
tv.setTextSize(30);
tv.setTextColor(this.getResources().getColorStateList(android.R.color.white));
}
}
}
src/com/example/hellotabhost/A_Activity.java
package com.example.hellotabhost;
import android.app.Activity;
import android.os.Bundle;
public class A_Activity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_tab_host);
}
}
src/com/example/hellotabhost/B_Activity.java
package com.example.hellotabhost;
import android.app.Activity;
import android.os.Bundle;
public class B_Activity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.title);
}
}
res/drawable/tab_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/tab_selected" />
<item android:state_focused="true" android:drawable="@drawable/tab_selected" />
<item android:state_selected="true" android:drawable="@drawable/tab_selected" />
<item android:drawable="@drawable/tab_normal" />
</selector>