给TabHost加上拖动效果

先说一下第一个示例,我做了一个可以拖动但是无法停留的效果,这个效果的实现是在TabHost的setCurrentTab方法里面加上动画,所以得自己写一个TabHost继承系统的TabHost并重写setCurrentTab方法。

那么我就把这个效果的代码给大家贴出来

package com.hwh.tab;


import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TabHost;

/*
 * 自定义TabHost,使tab切换的时候有动画效果
 */
public class CustomTabHost extends TabHost {
	private Animation slideLeftIn;
	private Animation slideLeftOut;
	private Animation slideRightIn;
	private Animation slideRightOut;

	private int tabCount;// tab页总数
	private int device_x; //屏幕宽

	public CustomTabHost(Context context, AttributeSet attrs) {
		super(context, attrs);
		Resources resources = getResources();
        DisplayMetrics metrics=resources.getDisplayMetrics();
        device_x=metrics.widthPixels;
        
		initAnima();
	}

	private void initAnima() {
		slideLeftIn=new TranslateAnimation(device_x, 0, 1, 1);
		slideLeftIn.setDuration(500);
		
		slideRightIn=new TranslateAnimation(-device_x,0,1,1);
		slideRightIn.setDuration(500);
		
		slideLeftOut=new TranslateAnimation(0,-device_x,1,1);
		slideLeftOut.setDuration(500);
		
		slideRightOut=new TranslateAnimation(0,device_x,1,1);
		slideRightOut.setDuration(500);
	}
	
	public void setDevice_X(int device_x)
	{
		this.device_x=device_x;
		initAnima();
	}

	public int getTabCount() {
		return tabCount;
	}

	@Override
	public void addTab(TabSpec tabSpec) {
		tabCount++;
		super.addTab(tabSpec);
	}

	
	@Override
	public void setCurrentTab(int index) {
		// index为要切换到的tab页索引,currentTabIndex为现在要当前tab页的索引
		int currentTabIndex = getCurrentTab();

		// 设置当前tab页退出时的动画
		if (null != getCurrentView()) {// 第一次进入MainActivity时,getCurrentView()取得的值为空
			if (currentTabIndex == (tabCount - 1) && index == 0) {// 处理边界滑动
				getCurrentView().startAnimation(slideLeftOut);
			} else if (currentTabIndex == 0 && index == (tabCount - 1)) {// 处理边界滑动
				getCurrentView().startAnimation(slideRightOut);
			} else if (index > currentTabIndex) {// 非边界情况下从右往左fleep
				getCurrentView().startAnimation(slideLeftOut);
			} else if (index < currentTabIndex) {// 非边界情况下从左往右fleep
				getCurrentView().startAnimation(slideRightOut);
			}
		}

		super.setCurrentTab(index);

		// 设置即将显示的tab页的动画
		if (currentTabIndex == (tabCount - 1) && index == 0) {// 处理边界滑动
			getCurrentView().startAnimation(slideLeftIn);
		} else if (currentTabIndex == 0 && index == (tabCount - 1)) {// 处理边界滑动
			getCurrentView().startAnimation(slideRightIn);
		} else if (index > currentTabIndex) {// 非边界情况下从右往左fleep
			getCurrentView().startAnimation(slideLeftIn);
		} else if (index < currentTabIndex) {// 非边界情况下从左往右fleep
			getCurrentView().startAnimation(slideRightIn);
		}
	}
}
这个思路是从网上找到的。TabHost的切换动画有了,怎么实现拖动呢。这个就很简单了,在Activity里重写OnTouth方法
@Override
    public boolean onTouchEvent(MotionEvent event) {
    	switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			start_x=(int) event.getX();
			break;
		case MotionEvent.ACTION_UP:
			end_x=(int) event.getX();
			int len=end_x-start_x;
			if(len<0)
			{
				if(Math.abs(len)>device_x/2)
				{
					index+=1;
				}
				//向右
			}if(len>0)
			{
				if(Math.abs(len)>device_x/2)
				{
					index-=1;
				}
			}
			if(index==count)
			{
				index=count-1;
			}
			if(index<0)
			{
				index=0;
			}
			tabHost.setCurrentTab(index);
			break;
		}
    	return false;
    }
这样就可以拖动了,但是没办法实现像ViewPager那样可以拖动一半的效果。

基于这个原因,我就想能不能把ViewPager和TabHost合并呢,但是有个问题,ViewPager要的是个View,而TabHost里面是Activity,怎么把Activity里的View给得到呢。

一个重要的类:LocalActivityManager,此类有个方法可以得到activity的View,使用startActivity(id, intent).getDecorView()即可得到,其中id可以随意写,intent就是对应activity的意图。思路说完了,下面把代码贴出来。

显示布局文件:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

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

    <android.support.v4.view.ViewPager
        android:id="@+id/vPager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1.0"
        android:background="#000000"
        android:flipInterval="30"
        android:persistentDrawingCache="animation" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" >
        </FrameLayout>
    </LinearLayout>

</TabHost>
Java代码:
package com.hwh.demo;

import java.util.ArrayList;
import java.util.List;

import android.app.LocalActivityManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class DemoActivity extends TabActivity {

        //页卡内容
        private ViewPager mPager;
        // Tab页面列表
        private List<View> listViews; 
        // 当前页卡编号
        private LocalActivityManager manager = null;
        private final Context context = DemoActivity.this;
        private TabHost mTabHost;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
                
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        mTabHost =  getTabHost();  
        mTabHost.addTab(mTabHost.newTabSpec("0").setIndicator(  
                "正在听").setContent(  
                new Intent(this, AActivity.class))); 
        
        mTabHost.addTab(mTabHost.newTabSpec("1").setIndicator(  
                "本地听").setContent(  
                new Intent(this, BActivity.class))); 
        
        mTabHost.addTab(mTabHost.newTabSpec("2").setIndicator(  
                "网络听").setContent(  
                new Intent(this, CActivity.class)));  
        
        mTabHost.setCurrentTab(0);  
        
        //tabhost改变同样改变ViewPager的内容
        mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			
			@Override
			public void onTabChanged(String tabId) {
				mPager.setCurrentItem(Integer.parseInt(tabId));
			}
		});
        
        manager = new LocalActivityManager(this, true);
        manager.dispatchCreate(savedInstanceState);
        
        InitViewPager();
    }
    
        /**
         * 初始化ViewPager
         */
        private void InitViewPager() {
                mPager = (ViewPager) findViewById(R.id.vPager);
                listViews = new ArrayList<View>();
                MyPagerAdapter mpAdapter = new MyPagerAdapter(listViews);
                Intent intent = new Intent(context, AActivity.class);
                listViews.add(getView("A", intent));
                Intent intent2 = new Intent(context, BActivity.class);
                listViews.add(getView("B", intent2));
                Intent intent3 = new Intent(context, CActivity.class);
                listViews.add(getView("C", intent3));
                mPager.setAdapter(mpAdapter);
                mPager.setCurrentItem(0);
                mPager.setOnPageChangeListener(new MyOnPageChangeListener());
        }
        
        
        /**
         * ViewPager适配器
         */
        public class MyPagerAdapter extends PagerAdapter {
                public List<View> mListViews;

                public MyPagerAdapter(List<View> mListViews) {
                        this.mListViews = mListViews;
                }

                @Override
                public void destroyItem(View arg0, int arg1, Object arg2) {
                        ((ViewPager) arg0).removeView(mListViews.get(arg1));
                }

                @Override
                public void finishUpdate(View arg0) {
                }

                @Override
                public int getCount() {
                        return mListViews.size();
                }

                @Override
                public Object instantiateItem(View arg0, int arg1) {
                        ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
                        return mListViews.get(arg1);
                }

                @Override
                public boolean isViewFromObject(View arg0, Object arg1) {
                        return arg0 == (arg1);
                }

                @Override
                public void restoreState(Parcelable arg0, ClassLoader arg1) {
                }

                @Override
                public Parcelable saveState() {
                        return null;
                }

                @Override
                public void startUpdate(View arg0) {
                }
        }


        /**
         * 页卡切换监听,ViewPager改变同样改变TabHost内容
         */
        public class MyOnPageChangeListener implements OnPageChangeListener {

                @Override
                public void onPageSelected(int arg0) {
                        switch (arg0) {
                        case 0:
                                mTabHost.setCurrentTab(0);  
                                break;
                        case 1:
                                mTabHost.setCurrentTab(1);
                                break;
                        case 2:
                                mTabHost.setCurrentTab(2);
                                break;
                        }
                }

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

                @Override
                public void onPageScrollStateChanged(int arg0) {
                }
        }
        
        private View getView(String id,Intent intent)
        {
                return manager.startActivity(id, intent).getDecorView();
        }
}
到此结束,如有不足之处请指出。


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值