您的位置:首页 > 移动开发 > Android开发

android学习笔记《三》:TabHost中自定义TabWidget

2011-12-20 11:01 281 查看
在写东西的时候经常会用到分页,这个是用TabHost来写,首先是layout文件的写法,这个比较固定,特别注意的是id,用系统的id,页面是基本固定下来的,代码如下

<?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="fill_parent"
android:layout_height="fill_parent">

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

<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" />

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


这里特别注意id是固定的,调用系统已经定义好的id。

一般的默认的tabHost这里就不说了,文章很多,稍微读一下就知道,这里详细的说一下自定义标签的视图,因为原生的实在是太丑了。

现在看一下TabHost的方法吧,这里边最重要的就是addTab(TabSpec)方法,跟newTabSpec(String) 方法,这里都用到了TabHost的内部类,TabSpec。所谓TabSpec就是在Tabwidget中显示的那一个个的小格子,addTab(TabSpec)就是增加一个小格子。而TabSpec的新建方法就是TabHost的newTabSpec(String)方法了,里边的String是该TabSpec的Tag。
TabSpec主要的方法就是setContent()和setIndicator(),设置的参数不同,设置的内容不同,setContent()是设置点击后的动作的,大部分情况是设置一个Intent来确定点击后显示的activity,另一个方法setIndicator(),其中两个方法一个是设置label的,还一个是设置label和icon的,这都是默认的布局,我们这里用到最后一个方法,就是setIndicator(View),传入的这个view就是自定义的视图了,想怎么定义就怎么定义。

取得视图有这么几种方法,一个是activity的setContentView(),这个是设置整个activity的根视图,传入的是一个xml文件,另一个是findViewById(),这个通过id来找对应的根视图的widget,还有一个就是通过 LayoutInflater.inflater()这个方法,这个是在指定的根视图中加入新的视图的方法,他也是传入的xml文件,下边详细的说一下LayoutInflater。
这个类用的还是很广的,毕竟在activity中加入其他的XML的视图都是用这个方法,要生成一个LayoutInflater有三种方法,
LayoutInflater inflater = LayoutInflater.from(this);
LayoutInflater inflater = getLayoutInflater();
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
这三种方法最终都是来调用最后一种方法,所以本质是一样的,
然后调用inflate方法将xml布局文件转成View
public View inflate (int resource, ViewGroup root, boolean attachToRoot),返回值为View类,

在View类中,也有inflate方法
public static View inflate (Context context, int resource, ViewGroup root)

通过以上方法获得view之后,再通过view.findViewById(),来获得该xml视图中的widget,并设置对应的值。

在之前的TabSpec中的setIndicator(View)方法中需要传入一个View值,可以新建一个方法,用inflate方法来获得视图,并且设置好内部的对应的值,返回该视图,传入setIndicator()中,就获得了一个TabSpec,传入TabHost的addTab(TabSpec)中,就新建好了一个完全是自定义的标签,然后运用该方法继续完成整个的TabWidget。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: