现在市面上app的主流框架大体分为两种:
一种是在主界面点击菜单按钮, 之后会滑出侧滑菜单, 之后进入到各个模块, 还有一种是
在主界面的下面放置若干个tab按钮, 点击按钮, 切换到不同的模块。 今天要讲的就是第二种的实现方式之一的FragmentTabHost.( 选 项卡) |
(实例)
1.activity_main.xml
<FrameLayout android:id="@+id/layout_frame" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" /> <android.support.v4.app.FragmentTabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom"> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" /> </android.support.v4.app.FragmentTabHost> |
2.tab.xml
<LinearLayout android:id="@+id/ll_tab" android:layout_width="match_parent" android:layout_height="50dp" android:background="@color/tab_bg" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/tab_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="@color/tab_bg" android:src="@mipmap/nav_icon_home_sel" /> <TextView android:id="@+id/tab_title" style="@style/CustomTextViewStyle03" android:layout_marginTop="3dp" android:text="首页" /> |
3,Activity中使用如下:
/** * tabhost选项卡 */ private TabWidget mTabWidget; private FragmentTabHost mTabHost; /** * 要加载所有的Fragment */ private Class<?>[] mFragments = {HomeFragment.class, OrderFragment.class, SelectCarFragment.class, CustomerFragment.class, MineFragment.class,}; private String[] titles = newString[]{"首页", "订单", "底价购车", "客服", "我的"}; mTabHost = findViewByIdNoCast(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.layout_frame); //获取一个TabWiidget mTabWidget = mTabHost.getTabWidget(); mTabWidget.setDividerDrawable(null); //为tabHost添加fragment int menuCount = mFragments.length; for (int i = 0; i < menuCount; i++) { TabHost.TabSpec spec = mTabHost.newTabSpec(titles[i]).setIndicator(getItemView(i)); mTabHost.addTab(spec, mFragments[i], null); } priv ate View getItemView(int index) { View view = LayoutInflater.from(this).inflate(R.layout.tab, null); TextView tv = (TextView) view.findViewById(R.id.tab_title); ImageView icon = (ImageView) view.findViewById(R.id.tab_icon); return view; } // 为FragmentTabHost添加点击事件 mTabHost.setOnTabChangedListener(newTabHost.OnTabChangeListener() { @Override public void onTabChanged(String tabName) { for (int i = 0; i < mTabWidget.getTabCount(); i++) { View view = mTabWidget.getChildTabViewAt(i); TextView tab_title = (TextView) view.findViewById(R.id.tab_title); ImageView tab_icon = (ImageView) view.findViewById(R.id.tab_icon); if (i == mTabHost.getCurrentTab()) { current_tab = i; tab_icon.setImageResource(iconS[i]); tab_title.setTextColor(Color.parseColor("#ffff4b14")); } else { tab_title.setTextColor(Color.rgb(162, 172, 181)); tab_icon.setImageResource(iconN[i]); } } } }); |
自写的方式第二种
XML
|