相信大家都用过qq,关于qq的界面是怎么实现的呢?其实它的界面就是我们今天要说的--用Fragment来实现tab。
首先,我们来说说这个方式的优点:
1.减少MainActivity类中的代码,将代码分配给相应的Fragment类中。
2.由于创建了多个Fragment来管理布局,因此后期维护更加容易,只需要更改相应的Fragment就行。
3.在单个Fragment中可以实现更多的功能,想一想qq的向右滑动与向左滑动。如果是viewpager,则不能这些功能。
好,话不多说,直接贴代码
MainActivity布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android_tab1.MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<include layout="@layout/top" />
</LinearLayout>
<FrameLayout
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
></FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<include layout="@layout/bottom" />
</LinearLayout>
</LinearLayout>
其他的xml代码,比如top.xml, buttom.xml, view1.xml, view2.xml, view3.xml, view4.xml代码都与上一文章中的一样的,这里我就不贴了。
WeixinFragment代码
package com.example.Fragment;
import com.example.android_tab2.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class WeixinFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.view1, container, false);
}
}
至于FriendFragment,AddressFragment,SettingsFragment的代码跟WeixinFragment的代码基本上是一样的,这里就不进行展示了。
MainActivity代码