Fragment进阶2——使用FragmentTabhost代替Tabhost

Fragment是Android 3.0 引入的新API,他使开发的效率更加高效,因为Tabhost已经不推荐使用了,现在android推荐使用FragmentTabhost,下面简单给个例子,相当于一个抛砖引玉的作用吧

系统大致结构:
一共四个选项卡,点击不同的选项卡切换到不同的fragment,在第一个fragment界面,我用ViewPager实现了一个图片轮播的功能,在第二个fragment界面实现了一个动态添加数据到GridView中的功能。
先看下activity_main.xml
<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" >

    <FrameLayout
        android:id="@+id/fl_main_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </FrameLayout>

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp" >
        </FrameLayout>
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

MainActivity.java如下

public class MainActivity extends FragmentActivity implements
        OnTabChangeListener {

    private final static String TAB_HOME = "home";
    private final static String TAB_LIFE = "life";
    private final static String TAB_ACCOOUNT = "account";
    private final static String TAB_MORE = "more";
    private long mExitTime = 0;
    private TabIndicatorView homeIndicator;
    private TabIndicatorView lifeIndicator;
    private TabIndicatorView accountIndicator;
    private TabIndicatorView moreIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        FragmentTabHost tabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        tabhost.setup(this, getSupportFragmentManager(), R.id.fl_main_content);

        //首页选项卡
        TabSpec spec = tabhost.newTabSpec(TAB_HOME);
        homeIndicator = new TabIndicatorView(this);
        homeIndicator.setTitle("首页");
        homeIndicator.setData(R.drawable.home_normal, R.drawable.home_press);
        spec.setIndicator(homeIndicator);
        tabhost.addTab(spec, HomeFragment.class, null);

        //生活选项卡
        spec = tabhost.newTabSpec(TAB_LIFE);
        lifeIndicator = new TabIndicatorView(this);
        lifeIndicator.setTitle("ͨ生活");
        lifeIndicator.setData(R.drawable.lifeon_normal,
                R.drawable.lifeon_press);
        spec.setIndicator(lifeIndicator);
        tabhost.addTab(spec, LifeFragment.class, null);

        //帐号选项卡
        spec = tabhost.newTabSpec(TAB_ACCOOUNT);
        accountIndicator = new TabIndicatorView(this);
        accountIndicator.setTitle("账户");
        accountIndicator.setData(R.drawable.zhanghu_normal,
                R.drawable.zhanghu_press);
        spec.setIndicator(accountIndicator);
        tabhost.addTab(spec, AccountFragment.class, null);

        //更多选项卡
        spec = tabhost.newTabSpec(TAB_MORE);
        moreIndicator = new TabIndicatorView(this);
        moreIndicator.setTitle("更多");
        moreIndicator.setData(R.drawable.gengduo_normal,
                R.drawable.gengduo_press);
        spec.setIndicator(moreIndicator);
        tabhost.addTab(spec, MoreFragment.class, null);

        tabhost.getTabWidget().setDividerDrawable(android.R.color.white);
        tabhost.setCurrentTabByTag(TAB_HOME);
        homeIndicator.setSelect(true);
        // 点击tab事件
        tabhost.setOnTabChangedListener(this);

    }

    @Override
    public void onTabChanged(String tabId) {
        homeIndicator.setSelect(false);
        lifeIndicator.setSelect(false);
        accountIndicator.setSelect(false);
        moreIndicator.setSelect(false);
        if (TAB_HOME.equals(tabId)) {
            homeIndicator.setSelect(true);
        } else if (TAB_LIFE.equals(tabId)) {
            lifeIndicator.setSelect(true);
        } else if (TAB_ACCOOUNT.equals(tabId)) {
            accountIndicator.setSelect(true);
        } else if (TAB_MORE.equals(tabId)) {
            moreIndicator.setSelect(true);
        }

    }

看下第一个fragment的实现吧,剩下的可以下载下来自己看下

public class HomeFragment extends Fragment {
    private View homeView;
    private ViewPager viewPager;
    private LinearLayout dot;

    private int[] images = new int[] { R.drawable.a, R.drawable.b,
            R.drawable.c, R.drawable.d, R.drawable.e, R.drawable.f };

    private ImageView[] mImageViews;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            mHandler.sendEmptyMessageDelayed(0, 4000);
        };
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        homeView = inflater.inflate(R.layout.fragment_home, container, false);
        initView();
        initData();

        return homeView;
    }

    /**
     * 初始化组件
     */
    private void initView() {
        viewPager = (ViewPager) homeView.findViewById(R.id.viewPager);
        dot = (LinearLayout) homeView.findViewById(R.id.dot);

    }

    private void initData() {
        initDots();

        mImageViews = new ImageView[images.length];
        for (int i = 0; i < mImageViews.length; i++) {
            mImageViews[i] = new ImageView(getActivity());
            ;
            mImageViews[i].setBackgroundResource(images[i]);
        }

        HomeAdapter adapter = new HomeAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                updateDot();

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

        int centerValue = Integer.MAX_VALUE / 2;
        int value = centerValue % images.length;
        viewPager.setCurrentItem(centerValue - value);

        updateDot();

        mHandler.sendEmptyMessageDelayed(0, 4000);
    }

    /**
     * 初始化dot点
     */
    private void initDots() {
        for (int i = 0; i < images.length; i++) {
            View view = new View(getActivity());
            LayoutParams params = new LayoutParams(8, 8);
            if (i != 0) {
                params.leftMargin = 5;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.selecter_dot);
            dot.addView(view);
        }
    }

    // 改变dot
    private void updateDot() {
        int currentPage = viewPager.getCurrentItem() % images.length;
        for (int i = 0; i < dot.getChildCount(); i++) {
            dot.getChildAt(i).setEnabled(i == currentPage);
        }

    }

    class HomeAdapter extends PagerAdapter {

        @Override
        public int getCount() {

            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {

            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ((ViewPager) container).addView(mImageViews[position
                    % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

}

布局文件如下:

<?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:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@drawable/blue_bg" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="首页"
            android:textColor="#fff"
            android:textSize="22sp" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="180dp" >

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/viewPager"
            android:orientation="vertical" >

            <LinearLayout
                android:id="@+id/dot"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="3dp"
                android:orientation="horizontal" >
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="首页"
            android:textSize="22sp" />
    </RelativeLayout>

</LinearLayout>

最后的效果如下


源代码

参考:
http://blog.csdn.net/xiaoyuan511/article/details/24882979?utm_source=tuicool&utm_medium=referral
http://www.itlanbao.com/code/100736.html

你可能感兴趣的:(Android开发,Fragment,tabhost)