package com.example.myfragmenttabhost;
import android.app.FragmentHostCallback;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabWidget;
import android.widget.TextView;
import org.w3c.dom.Text;
/**
* 注意,布局文件的id 必须是Android固定标签,本身就存在的
* FragmentTabHost框架 切换Fragment
*/
public class MainActivity extends AppCompatActivity {
FragmentTabHost tabHost;
FrameLayout tabContent;
TabWidget tabs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = findViewById(R.id.tabHost);//获取FragmentTabHost控件
tabHost.setup(this,getSupportFragmentManager(),android.R.id.tabcontent);//设置填充内容
newTab( tabHost, "首页", R.drawable.icon_tab_home ,FragmentShouye.class);
newTab( tabHost, "服务", R.drawable.icon_tab_service ,FragmentService.class);
newTab( tabHost, "我的", R.drawable.icon_tab_mine ,FragmentMine.class);
}
/**
* 设置tab,包括其名称和资源文件; tabName关联对应的Fragment
* @param tabHost
* @param tabName
* @param resId
* @param fragmentClass
*/
private void newTab(FragmentTabHost tabHost, String tabName, int resId,Class fragmentClass) {
View view = LayoutInflater.from(this).inflate(R.layout.tab_layout,null);
ImageView tabImg=view.findViewById(R.id.tabImg);
tabImg.setImageResource(resId);
TextView tabNames=view.findViewById(R.id.tabName);
tabNames.setText(tabName);
FragmentTabHost.TabSpec tabSpec =tabHost.newTabSpec(tabName).setIndicator(view);
tabHost.addTab(tabSpec,fragmentClass,null);
}
}
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tabHost" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="false"> <RelativeLayout 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" /> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fcfcfc" android:padding="6dp" /> </LinearLayout> </RelativeLayout> </android.support.v4.app.FragmentTabHost>