滑动导航栏,标签页切换

弄了个gif录制工具,看下我的动图有没有成功,效果如下

滑动导航栏,标签页切换_第1张图片


我先是找到了一个仿网易新闻客户端的例子,

MainActivity 

package com.example.smooth;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private HorizontalScrollView mHorizontalScrollView ;
	private LinearLayout mLinearLayout;
	private ViewPager pager;
	private ImageView mImageView;
	private int mScreenWidth;
	private int item_width;
	
	private int endPosition;
	private int beginPosition;
	private int currentFragmentIndex;
	private boolean isEnd;
	
	private ArrayList fragments;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		mScreenWidth = dm.widthPixels;
		mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv_view);
		mLinearLayout = (LinearLayout) findViewById(R.id.hsv_content);
		mImageView = (ImageView) findViewById(R.id.img1);
		item_width = (int) ((mScreenWidth / 4.0 + 0.5f));
		mImageView.getLayoutParams().width = item_width;
		
		pager = (ViewPager) findViewById(R.id.pager);
		// 初始化导航
		initNav();
		// 初始化viewPager
		initViewPager();
	}

	private void initViewPager() {
		fragments = new ArrayList();
    	for (int i = 0; i < 7; i++) {
    		Bundle data = new Bundle();
    		data.putString("text", (i+1)+"");
    		BaseFragment fragment = new BaseFragment();
    		fragment.setArguments(data);
    		fragments.add(fragment);
		}
    	MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments);
		pager.setAdapter(fragmentPagerAdapter);
		fragmentPagerAdapter.setFragments(fragments);
		pager.setOnPageChangeListener(new MyOnPageChangeListener());
		pager.setCurrentItem(0);
	}
	
	private void initNav() {
		for (int i = 0 ; i < 7 ; i++) {
			RelativeLayout layout = new RelativeLayout(this);
			TextView view = new TextView(this);
			view.setText("第"+(i+1)+"个");
			RelativeLayout.LayoutParams params =  new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.CENTER_IN_PARENT);
			layout.addView(view, params);
			mLinearLayout.addView(layout, (int)(mScreenWidth/4 + 0.5f), 50);
			layout.setOnClickListener(this);
			layout.setTag(i);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
	
	private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
		private ArrayList fragments; 
		private FragmentManager fm;

	    public MyFragmentPagerAdapter(FragmentManager fm) {
	        super(fm);
	    	this.fm = fm;
	    }

	    public MyFragmentPagerAdapter(FragmentManager fm, ArrayList fragments) {
	        super(fm);
			this.fm = fm;
	        this.fragments = fragments;
	    }

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

	    @Override
	    public Fragment getItem(int position) {
	        return fragments.get(position);
	    }

	    @Override
	    public int getItemPosition(Object object) {
	        return POSITION_NONE;
	    }
	    
	    
		public void setFragments(ArrayList fragments) {
			if(this.fragments != null){
				FragmentTransaction ft = fm.beginTransaction();
				for(Fragment f:this.fragments){
					ft.remove(f);
				}
				ft.commit();
				ft=null;
				fm.executePendingTransactions();
			}
			this.fragments = fragments;
			notifyDataSetChanged();
		}
		
		
		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
		    Object obj = super.instantiateItem(container, position);
		    return obj;
		}
			
	}
	
	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(final int position) {
			Animation animation = new TranslateAnimation(endPosition, position* item_width, 0, 0);
			
			beginPosition = position * item_width;
			
			currentFragmentIndex = position;
			if (animation != null) {
				animation.setFillAfter(true);
				animation.setDuration(0);
				mImageView.startAnimation(animation);
				mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1) * item_width , 0);
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			if(!isEnd){
				if(currentFragmentIndex == position){
					endPosition = item_width * currentFragmentIndex + 
							(int)(item_width * positionOffset);
				}
				if(currentFragmentIndex == position+1){
					endPosition = item_width * currentFragmentIndex - 
							(int)(item_width * (1-positionOffset));
				}
				
				Animation mAnimation = new TranslateAnimation(beginPosition, endPosition, 0, 0);
				mAnimation.setFillAfter(true);
				mAnimation.setDuration(0);
				mImageView.startAnimation(mAnimation);
				mHorizontalScrollView.invalidate();
				beginPosition = endPosition;
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_DRAGGING) {
				isEnd = false;
			} else if (state == ViewPager.SCROLL_STATE_SETTLING) {
				isEnd = true;
				beginPosition = currentFragmentIndex * item_width;
				if (pager.getCurrentItem() == currentFragmentIndex) {
					// 未跳入下一个页面
					mImageView.clearAnimation();
					Animation animation = null;
					// 恢复位置
					animation = new TranslateAnimation(endPosition, currentFragmentIndex * item_width, 0, 0);
					animation.setFillAfter(true);
					animation.setDuration(1);
					mImageView.startAnimation(animation);
					mHorizontalScrollView.invalidate();
					endPosition = currentFragmentIndex * item_width;
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		pager.setCurrentItem((Integer)v.getTag());
	}
}


BaseFragment 

package com.example.smooth;

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

public class BaseFragment extends Fragment {

	private String text="";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Bundle args = getArguments();
		text = args != null ? args.getString("text") : "";
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view =inflater.inflate(R.layout.layout_1, null); 
		TextView tv_fragment = (TextView) view.findViewById(R.id.tv_fragment);
		tv_fragment.setText(text);
		return view;
	}
}


activity_main.xml



	
	    
		    
		    
		    
	
	
	    
	



layout_1.xml



    



很简单有没有?但是!但是来咯!!

它这个是有7个分类,而我的项目只需要3个,所以我改变了数量,然后就发现问题了

滑动没有问题,问题出在点击的时候

当我点击第二个的时候,下划线停留在第二个下面,然后我点击第三个,发现下划线先回到第一个下面在滑到第三个下面,也就是说没有直接从第二个向第三个移动,不知道是否看得清晰

滑动导航栏,标签页切换_第2张图片



平移的起始点并没有问题,我实在想不出是哪里出了问题,不过我想明白了另外一件事,所谓的滑动导航,不过就是给下划线加个动画而已,想通了就容易解决了。~~~


首先在布局文件内,tab的下方添加一个view作为待会要移动的下划线

    

动画代码跟以上的例子类似,增加了一个字体的改变

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

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

@ContentView(R.layout.fragment_customer)
public class FragmentCustomer extends FragmentBase {

    @ViewInject(value = R.id.tv_custom_deal)
    TextView tvDeal;

    @ViewInject(value = R.id.tv_custom_target)
    TextView tvTarget;

    @ViewInject(value = R.id.tv_custom_agent)
    TextView tvAgent;

    @ViewInject(value = R.id.view1)
    View view1;

    @ViewInject(value = R.id.vp_view)
    ViewPager mViewPager;

    FragmentCustomerDeal fragDeal = new FragmentCustomerDeal();
    FragmentCustomerTarget fragTarget = new FragmentCustomerTarget();
    FragmentCustomerAgent fragAgent = new FragmentCustomerAgent();
    private FragmentPagerAdapter mAdapter;

    private List mFragments = new ArrayList();

    private int mScreenWidth;
    private int item_width;

    private int endPosition;
    private int beginPosition = 0;
    private int currentFragmentIndex;


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TAG = "======FragmentCustomer=====";

        LogOut("客户圈界面启动", TAG);
        DisplayMetrics dm = new DisplayMetrics();
        activityBasic.getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScreenWidth = dm.widthPixels;
        item_width = (int) ((mScreenWidth / 3.0 + 0.5f));
        view1.getLayoutParams().width = item_width;

        mFragments.add(fragDeal);
        mFragments.add(fragTarget);
        mFragments.add(fragAgent);

        mAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {

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

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };
        mViewPager.setAdapter(mAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageSelected(int position) {
                resetColor();
                switch (position) {
                    case 0:
                        tvDeal.setTextColor(getResources().getColor(R.color.textChecked));
                        break;
                    case 1:
                        tvTarget.setTextColor(getResources().getColor(R.color.textChecked));
                        break;
                    case 2:
                        tvAgent.setTextColor(getResources().getColor(R.color.textChecked));
                        break;
                    default:
                        break;
                }
                currentFragmentIndex = position;
                Animation animation = new TranslateAnimation(beginPosition, position * item_width, 0, 0);

                beginPosition = position * item_width;

                if (animation != null) {
                    animation.setFillAfter(true);
                    animation.setDuration(0);
                    view1.startAnimation(animation);
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                if (currentFragmentIndex == position) {
                    endPosition = item_width * currentFragmentIndex +
                            (int) (item_width * positionOffset);
                }
                if (currentFragmentIndex == position + 1) {
                    endPosition = item_width * currentFragmentIndex -
                            (int) (item_width * (1 - positionOffset));
                }

                Animation mAnimation = new TranslateAnimation(beginPosition, endPosition, 0, 0);
                mAnimation.setFillAfter(true);
                mAnimation.setDuration(0);
                view1.startAnimation(mAnimation);
                beginPosition = endPosition;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void resetColor() {
        tvDeal.setTextColor(getResources().getColor(R.color.TabNormal));
        tvTarget.setTextColor(getResources().getColor(R.color.TabNormal));
        tvAgent.setTextColor(getResources().getColor(R.color.TabNormal));
    }

    @Event(value = {R.id.ll_custom_deal, R.id.ll_custom_target, R.id.ll_custom_agent})
    private void onTabClick(View view) {
        resetColor();
        switch (view.getId()) {
            case R.id.ll_custom_deal:
                tvDeal.setTextColor(getResources().getColor(R.color.textChecked));
                mViewPager.setCurrentItem(0);
                currentFragmentIndex = 0;
                break;
            case R.id.ll_custom_target:
                tvTarget.setTextColor(getResources().getColor(R.color.textChecked));
                mViewPager.setCurrentItem(1);
                currentFragmentIndex = 1;
                break;
            case R.id.ll_custom_agent:
                tvAgent.setTextColor(getResources().getColor(R.color.textChecked));
                mViewPager.setCurrentItem(2);
                currentFragmentIndex = 2;
                break;
            default:
                break;
        }
        Animation animation = new TranslateAnimation(beginPosition, currentFragmentIndex * item_width, 0, 0);

        beginPosition = currentFragmentIndex * item_width;

        if (animation != null) {
            animation.setFillAfter(true);
            animation.setDuration(0);
            view1.startAnimation(animation);
        }

    }

}

我记得我刚刚写仿网易新闻APP的时候我用的是viewpagerIndicator,其实现在这样看下来就只是加个动画而已,原来觉得很难很难的东西,想清楚了也就那么回事。多想想多交流!


你可能感兴趣的:(布局)