仿oschina 主界面的实现(一) -------FragmentTabHost+Fragment

FragmentTabHost+Fragment

官网的API dome

Special TabHost that allows the use of Fragment objects
for its tab content. When placing this in a view hierarchy, after inflating the hierarchy you must call setup(Context,
FragmentManager, int)
 to complete the initialization of the tab host.

import com.example.android.supportv4.R;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;

/**
 * This demonstrates how you can implement switching between the tabs of a
 * TabHost through fragments, using FragmentTabHost.
 */
public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_tabs);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                FragmentStackSupport.CountingFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                LoaderCursorSupport.CursorLoaderListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
                LoaderCustomSupport.AppListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
                LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);
    }
}

This can also be used inside of a fragment through fragment nesting:

import com.example.android.supportv4.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentTabsFragmentSupport extends Fragment {
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                FragmentStackSupport.CountingFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                LoaderCursorSupport.CursorLoaderListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
                LoaderCustomSupport.AppListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
                LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);

        return mTabHost;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}

常用的方法

Public Methods
void addTab(TabHost.TabSpec tabSpec, Class<?>
clss, Bundle args)
void onTabChanged(String tabId)
void setOnTabChangedListener(TabHost.OnTabChangeListener l)

Register a callback to be invoked when the selected state of any of the items in this list changes

void setup()

This method is deprecated. Don‘t call the original TabHost setup, you must instead call setup(Context,
FragmentManager)
 or setup(Context,
FragmentManager, int)
.

void setup(Context context, FragmentManager manager)
void setup(Context context, FragmentManager manager,
int containerId)

效果图

main_tab_explore:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/widget_bar_explore_over" android:state_selected="true"></item>
    <item android:drawable="@drawable/widget_bar_explore_nor" ></item>
</selector>

activity_main:

<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.skyfin.oschina.MainActivity" >

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <com.skyfin.oschina.MyFragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/Fragment_tab_bg">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />
    </com.skyfin.oschina.MyFragmentTabHost>

</LinearLayout>

MainActivity

package com.skyfin.oschina;

import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;

public class MainActivity extends FragmentActivity {

	String old_tag;
	private MyFragmentTabHost mTabHost;

	private LayoutInflater layoutInflater;

	private View fragmentQuickoption;

	private Class fragmentArray[] = {FragmentNews.class,
			FragmentTweet.class,FragmentQuickoption.class,
			FragmentExplore.class,FragmentMe.class};

	private int mImageArray[] = {R.drawable.main_tab_news,
			R.drawable.main_tab_tweet,R.drawable.main_tab_quickoption,
			R.drawable.main_tab_explore,R.drawable.main_tab_me};

	private String mTextArray[]={
			"综合","动弹","添加","发现","我"
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView(){

		// 实例化布局对象
        layoutInflater = LayoutInflater.from(this);

        // 实例化TabHost对象,得到TabHost
        mTabHost = (MyFragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        // 得到fragment的个数
        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
        	//View indicator = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_item_btn_view, null);
            // 为每一个Tab按钮设置图标、文字和内容
            TabSpec tabSpec = mTabHost.newTabSpec(mTextArray[i])
                    .setIndicator(getTabItemView(i));
            // 将Tab按钮添加进Tab选项卡中
            if(i == 2)
            {
            	//indicator.setVisibility(View.INVISIBLE);
            	mTabHost.setNoTabChangedTag(mTextArray[i]);
            }
            //tabSpec.setIndicator(indicator);
            /*tabSpec.setContent(new TabContentFactory(){

				@Override
				public View createTabContent(String tag) {
					// TODO Auto-generated method stub
					return null;
				}

            });*/
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            // 设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i)
                    .setBackgroundResource(R.color.Fragment_tab_bg);
            //去掉竖线
            mTabHost.getTabWidget().setDividerDrawable(null);
        }
        //设置按钮的监听
        mTabHost.setOnTabChangedListener(new OnTabChangedListener());

	}
	/**
	 * 按钮的监听的类
	 * @author Skyfin
	 *
	 */
	class OnTabChangedListener implements OnTabChangeListener {

		@Override
		public void onTabChanged(String tabId) {
			// TODO Auto-generated method stub
			//Toast.makeText(getApplication(), tabId,Toast.LENGTH_SHORT).show();
			if (old_tag != tabId) {
				Toast.makeText(getApplicationContext(), tabId, Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(), "添加", Toast.LENGTH_SHORT).show();
			}
			old_tag = tabId;

		}

	}
	  /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);

        if(index != 2){
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextArray[index]);
        }else {
        	view = layoutInflater.inflate(R.layout.tab_item_btn_view, null);
        	ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        	imageView.setImageResource(mImageArray[index]);
		}
        return view;
    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

MyFragmentTabHost

package com.skyfin.oschina;

import android.content.Context;
import android.support.v4.app.FragmentTabHost;
import android.util.AttributeSet;

public class MyFragmentTabHost extends FragmentTabHost {

	private String mCurrentTag;

	private String mNoTabChangedTag;

	public MyFragmentTabHost(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public void onTabChanged(String tag) {

		if (tag.equals(mNoTabChangedTag)) {
			setCurrentTabByTag(mCurrentTag);
		} else {
			super.onTabChanged(tag);
			mCurrentTag = tag;
		}
	}

	public void setNoTabChangedTag(String tag) {
		this.mNoTabChangedTag = tag;
	}
}

Fragment:

package com.skyfin.oschina;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentNews extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_news, container, false);
	}
}

代码下载:http://download.csdn.net/detail/u012938203/8989689

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-30 00:09:38

仿oschina 主界面的实现(一) -------FragmentTabHost+Fragment的相关文章

Android ActionBar应用实战,高仿微信主界面的设计

转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/26365683 经过前面两篇文章的学习,我想大家对ActionBar都已经有一个相对较为深刻的理解了.唯一欠缺的是,前面我们都只是学习了理论知识而已,虽然知识点已经掌握了,但是真正投入到项目实战当中时会不会掉链子还很难说.那么不用担心,本篇文章我就将带领大家一起进入ActionBar的应用实战,将理论和实践完美结合到一起. 如果你还没有看过我的前两篇文章,建议先去阅读一下 Andr

使用FragmentTabHost和ViewPager实现仿微信主界面策划

最近看到很多界面主页都差不多,决定研究研究写出来,以后直接拿来用,不做代码的轮子,多总结,多学习 还是废话少说,先上图 介绍一下我的代码: 首先是布局文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=&quo

Android利用ViewPager仿微信主界面-android学习之旅(78)

首先是介绍ViewPager这个控件 ,这个控件需要pagerAdapter作为容器来提供数据,同时pagerAdapter的数据源是View数组 效果图如下 部分代码如下,实现如下的方法 mPagerAdapter = new PagerAdapter(){ @Override public int getCount() { return mViews.size(); } @Override public boolean isViewFromObject(View view, Object o

Android 之高仿微信主界面

源码下载:  http://files.cnblogs.com/aibuli/WeChatSample.zip 主界面主要使用ActionBar来完成.  要实现这个效果,第一步当然是编辑menu目录下的main.xml文件. <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:

仿微信主界面导航栏图标字体颜色的变化

在所有的移动产品中,微信的界面做的很简洁,简单,我对微信主界面影响最深的就是微信底部导航栏的图标,以及字体颜色的变化,一直都想实现以下,今天有空,就大体的模仿者做了一遍. 效果图如下: 分析: 底部主要分为图标的渐变,字体颜色的渐变. 图标的颜色的渐变:主要是通过canvas绘制两个不同的图片,控制其图片的alpha透明度,来达到图标的渐变. 字体颜色:字体颜色就很好说了,Animator动画框架应该很熟悉了,在Animator框架中,有一个TypeEven是来计算十六进制色值的,我们可以通过A

仿微信主界面

跟着慕课网的教学视频学习了如何制作微信的主界面,因为还有一些地方并没有完全搞懂,所以这里主要是记录下整个制作的过程,方便以后的学习! 效果图如图所示: 实现了点击下面tab切换fragment以及滑动切换tab的功能,同时滑动时,下面tab的icon会实现颜色渐变的效果. 首先是主界面的布局: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bunschen="

高仿美团主界面&lt;一&gt;

声明:本demo还未完善,正在持续更新中... 先上图吧: 这个小demo资源图片全是用青花瓷抠出来的,现在只是完成了 一部分.会持续更行中...有兴趣的朋友可以关注我,我们一起coding,一起分享. 然后这个demo很简单.但是有一些小细节可以和大家分享. 相信用过美团的同鞋都知道,美团的主界面. 效果动画图如下: git图 很明显美团的主界面是一个tableView 如上图的scrollView是tableView的一个cell. 快速创建一个cell并传递一个模型. (UITableVi

ViewPager学习之仿微信主界面

因为素材的原因,这里都是从网上找的图片,所以所谓的仿微信实际上最后成了下图这货...,点击变色也是自己用的windows自带画图的颜料桶填充的空白... 直接上主代码: package com.example.tabandviewpage ; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.support

高仿微信主界面:ViewPage+Fragment 不预加载Fragment 也不会销毁Fragment

微信支持下面四个Tab滑动,之前做的demo,遇到两个问题,1:Fragment会预加载,2:创建过的Fragment,来回滑动,会销毁重新创建.今天我这个demo,就要解决这两个问题.第一个问题需要导入一个新的V4包,最后我会提供,ViewPage要设置 mViewPager .setOffscreenPageLimit(0);这样的就能解决预加载的问题.第二个问题:我贴上代码: package com.example.fragmentviewpage; import java.util.Ar