超级简单的底部导航按钮
程序员文章站
2022-06-09 21:27:04
...
用FragmentTabHost和LayoutInflater实现的底部导航按钮
先看一下布局文件
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/maintab_toolbar_bg" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
MainActivity
public class MainActivity extends FragmentActivity {
// 定义FragmentTabHost对象
private FragmentTabHost mTabHost;
// 定义一个布局
private LayoutInflater layoutInflater;
// 定义数组来存放Fragment界面
private Class fragmentArray[] = { FragmentPage1.class, FragmentPage2.class,
FragmentPage3.class, FragmentPage4.class, FragmentPage5.class };
// 定义数组来存放按钮图片
private int mImageViewArray[] = { R.drawable.btn_common,
R.drawable.btn_assets, R.drawable.btn_look,
R.drawable.btn_position, R.drawable.btn_lable };
// Tab选项卡的文字
private String mTextviewArray[] = { "常用", "资产", "标签", "位置采集", "查看" };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//
setContentView(R.layout.activity_main);
initView();
}
/**
* 初始化组件
*/
private void initView() {
// 实例化布局对象
layoutInflater = LayoutInflater.from(this);
// 实例化TabHost对象,得到TabHost
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
// 得到fragment的个数
int count = fragmentArray.length;
for (int i = 0; i < count; i++) {
// 为每一个Tab按钮设置图标、文字和内容
TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
.setIndicator(getTabItemView(i));
// 将Tab按钮添加进Tab选项卡中
mTabHost.addTab(tabSpec, fragmentArray[i], null);
// 设置Tab按钮的背景
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundResource(R.drawable.tab_selector_background);
}
}
/**
* 给Tab按钮设置图标和文字
*/
private View getTabItemView(int index) {
View view = layoutInflater.inflate(R.layout.tab_item_view, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
imageView.setImageResource(mImageViewArray[index]);
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(mTextviewArray[index]);
return view;
}
}
FragmentPage1
在这里复制5fragment就可以了
public class FragmentPage1 extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return view = inflater.inflate(R.layout.fragment_1, null);
}
}
最后的效果