好久没有Android方面的文章出来,今天正好有时间就来写点界面方面的东西。


Fragment的含义是“碎片”,在Android中Fragment不能单独使用,必须嵌入到某个Activity中。下面我们通过一个Tab切换的一个底部菜单栏例子看看Fragment如何使用。


1. 准备工作

Fragment是Android 3.0以后提出来的概念,那么我们的工程希望能在手机上运行,我们需要建立一个Android 4.0的工程。

另外我在工程中大量用到了xUtils工具类(这是个很实用的工具类,我会以后单独开系列进行讲解),所以需要将其lib文件添加到classpath中。


2. AndroidManifest.xml

这个比较简单,主要是添加权限供xUtils使用:
    <!-- 添加的权限,供xUtils使用 -->    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


3. 准备资源

我们需要准备的资源主要包括:

3.1 图片按钮文件

这里我准备了icon1~4, icon_on1~4的两组四个按钮的按下和弹起的图片。

3.2 背景选择器

Android有一种特殊类型的资源xml文件叫背景选择器,对于每个按钮的各种状态可以分别定义,如下就是其中之一的selector:
<?xml version="1.0" encoding="utf-8"?><selector  xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/icon_1"  android:state_selected="true"/>    <item android:drawable="@drawable/icon_on_1"/></selector>
其他三个文件都类似,全部将其放到res/drawable目录中。

3.3 Activity布局

主Activity的布局如下:

<?xml version="1.0" encoding="UTF-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@color/gray"    android:orientation="vertical" ><!-- Frame容器,用于TabHost切换Frame内容 -->    <FrameLayout        android:id="@+id/main_fragmentContainer"        android:layout_width="match_parent"        android:layout_height="0dip"        android:background="@color/white"        android:layout_weight="1"/><!-- 标签按钮栏 -->    <android.support.v4.app.FragmentTabHost        android:id="@+id/main_fragmenttabhost"        android:layout_width="match_parent"        android:layout_height="wrap_content">    </android.support.v4.app.FragmentTabHost></LinearLayout>

很简单吧?FrameLayout用于做Fragment的容器,FragmentTabHost中存放工具栏按钮。


3.4 导航栏按钮布局

我这里省略了导航栏的布局。如果需要可以在android.support.v4.app.FragmentTabHost内部增加Layout控件来实现。 导航栏按钮的布局如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="fill_parent"              android:layout_height="fill_parent"              android:gravity="center"              android:orientation="vertical">    <!-- 通过使用TextView加上代码中使用tv.setCompoundDrawables的方式更为简洁    <TextView                android:id="@+id/tabButton"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:textColor="@color/textgray"                android:textSize="12sp"                android:clickable="false"                android:background="@android:color/transparent"                android:gravity="center"                />                --><ImageView android:id="@+id/tabImage"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:paddingTop="10dip"                android:contentDescription="@string/app_name" />        <Button                android:id="@+id/tabButton"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:textColor="@color/textgray"                android:textSize="12sp"                android:clickable="false"                android:background="@android:color/transparent"                android:gravity="center"/></LinearLayout>

3.5 res/values

res/values下还有如下的资源文件:

3.5.1 color.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <color name="gray">#484848</color>    <color name="white">#FFFFFF</color>    <color name="black">#000000</color>    <color name="textgray">#8f8f8f</color>    <color name="background">#00FF00</color></resources>

3.5.2 strings.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">FragmentActivityDemo</string>    <string name="action_settings">Settings</string>    <string name="hello_world">Hello world!</string>    <!-- activity_main -->    <string name="tab_1">Tab1</string>    <string name="tab_2">Tab2</string>    <string name="tab_3">Tab3</string>    <string name="tab_4">Tab4</string></resources>

4. Java源代码

4.1 Fragment代码

Fragment代码其实非常简单,和Activity稍有不同,需要继承自Fragment和重写onCreateView方法:
public class Fragment1 extends Fragment {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// 通过布局文件生成一个新的view        View view = inflater.inflate(R.layout.fragment_1, container, false);        // 将view与工具类ViewUtils做一次注入(xUtils要求)        ViewUtils.inject(this, view);return view;}

4.2 Activity代码

Activity的代码略显复杂,但主要是在初始化时创建Tab并嵌入Fragment:
@ContentView(R.layout.activity_main)public class MainActivity extends FragmentActivity {@ViewInject(R.id.main_fragmenttabhost)private FragmentTabHost main_tabhost;@SuppressWarnings("rawtypes")private Class fragmentClasses[] = { Fragment1.class, Fragment2.class,Fragment3.class, Fragment4.class };// 关于Tab按钮icon的设置保存在/drawable目录下的几个xml文件中private int tabIconRes[] = { R.drawable.tab_icon_1, R.drawable.tab_icon_2,R.drawable.tab_icon_3, R.drawable.tab_icon_4 };private int tabTextRes[] = { R.string.tab_1, R.string.tab_2,R.string.tab_3, R.string.tab_4 };@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 注入ViewUtils.inject(this);initTabs();}private void initTabs() {// 设置Frame界面的容器main_tabhost.setup(this, getSupportFragmentManager(),R.id.main_fragmentContainer);for (int i = 0; i < fragmentClasses.length; i++) {// 设置每一个Tab按钮TabHost.TabSpec tabSpec = main_tabhost.newTabSpec(getString(tabTextRes[i])).setIndicator(getTabItemView(i));main_tabhost.addTab(tabSpec, fragmentClasses[i], null);main_tabhost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.selector_navbar_background);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}private View getTabItemView(int i) {LayoutInflater layoutInflater = LayoutInflater.from(this);View view = layoutInflater.inflate(R.layout.tabbar_item, null);Resources res = this.getResources();// 设置按钮文字Button btn = (Button) view.findViewById(R.id.tabButton);btn.setText(res.getText(tabTextRes[i]));// 如果是TextView可以用下面的代码设置Image,完全不使用ImageView//Drawable drawable = res.getDrawable(tabIconRes[i]);//Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.tab_icon_sample);//drawable.setBounds(0, 0, bmp.getWidth(), bmp.getHeight());//btn.setCompoundDrawables(null, drawable, null, null);ImageView img = (ImageView) view.findViewById(R.id.tabImage);img.setImageResource(tabIconRes[i]);return view;}}



更多相关文章

  1. android中解析文件的三种方式
  2. Android如何获取多媒体文件信息
  3. [置顶] Android中对Log日志文件的分析
  4. android线性布局参数详解
  5. 分享自己在项目中对android文件系统的一些认识
  6. 无废话Android之android下junit测试框架配置、保存文件到手机内
  7. Android动态加载外部jar包及jar包中图片等资源文件
  8. 关于Android初级逻辑思考(续)——android文件夹讲解
  9. Android入门:使用Android自带媒体库读取MP3文件

随机推荐

  1. mvp过渡到mvvm(Android(安卓)架构组件)
  2. android音乐播放器实现
  3. 打开SDK Manager检查Android SDK下载和更
  4. 2010.12.10(3)——— android MapView 以
  5. Android 任务共用性Affinity
  6. Android 自定义 Dialog 大小 位置 样式
  7. android项目案例6- 基于Android studio的
  8. android 地图
  9. Android进阶(十八)AndroidAPP开发问题汇
  10. Android动画效果