FragmentTabHost实现标签卡效果
转载请注明原文链接:http://www.cnblogs.com/yanyojun/p/8099523.html
代码已上传到github:https://github.com/YanYoJun/FragmentTabHostDemo
上一篇有讲过使用ViewPager来实现标签卡效果的。这一篇讲一下使用FragmentTabHost实现标签卡效果
惯例先上截图

第一步、布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="true"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.app.FragmentTabHost
android:id="@+id/tab_host"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></FrameLayout>
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FFFFFF"
android:divider="@null"
android:padding="5dp"></TabWidget>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</LinearLayout>第二步代码实现:
package com.plbear.yyj.fragmenttabhostdemo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var titles = arrayOf("tab1","tab2","tab3","tab4")
var tabImg = arrayOf(R.drawable.tab,R.drawable.tab,R.drawable.tab,R.drawable.tab)
var fragments = arrayOf(MyFragment1::class.java, Fragment2::class.java, Fragment3::class.java, Fragment4::class.java)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initTabWidget()
}
fun initTabWidget(){
tab_host.setup(this,supportFragmentManager,android.R.id.tabcontent)
for(i in 0..3){
var v = layoutInflater.inflate(R.layout.layout_tab,null)
var img = v.findViewById<android.widget.ImageView>(R.id.iv_tab)
var lab = v.findViewById<TextView>(R.id.tv_tab)
img.setImageResource(tabImg[i])
lab.setText(titles[i])
tab_host.addTab(tab_host.newTabSpec(""+i).setIndicator(v),fragments[i],null)
}
tab_host.setCurrentTabByTag("1")
}
}主要的实现都在initTabWidget中