最近在研究网易新闻,发现它的左侧竟然是用TabHost实现的,TabHost的选项卡实现上下很简单(直接修改布局文件),本篇文章说下怎么实现“左侧TabHost”。
先给出实现的原理,TabHost的选项卡实际上是TabWidget控件,TabWidget继承自LinearLayout,所以实现“左侧TabHost”其实只有两个步骤:
1. 修改TabWidget的布局参数,将android:orientation属性设置为vertical
2. 改变TabWidget添加一个选项卡时的LayoutParams
下面结合代码详细说下,整个工程的目录,比较简单:
activity_main.xml的代码,详细关注下TabWidget的布局参数:
<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"
tools:context=".MainActivity" >
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="100dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="top">
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#123" >
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#456" >
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#789" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
MainActivity的代码,详细关注for循环里面重新设置TabWidget子View的LayoutParams参数:
package com.example.tabhost;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TabHost;
import android.widget.TabWidget;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1")
.setContent(R.id.tab1));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("tab2")
.setContent(R.id.tab2));
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3")
.setContent(R.id.tab3));
//设置TabWidget的布局参数
TabWidget tabWidget = tabHost.getTabWidget();
for (int i = 0; i < tabWidget.getChildCount(); i++) {
View child = tabWidget.getChildAt(i);
LinearLayout.LayoutParams lp =
(LayoutParams) child.getLayoutParams();
lp.width = LayoutParams.MATCH_PARENT;
lp.height = 80;
lp.weight = 0.0f;
}
}
}
好了,到此结束,一个很简单的Demo,最后的运行效果如下图,源码下载链接: 点击下载源码