Tab切换动画滑动效果的一个简单实现

时间:2022-11-30 12:37:46

看到很多应用程序中,点击切换tab时,之前选中的tab会滑动到点击重新选中的tab上。


最初是在htc的手机上看到这个效果的,htc手机的系统程序tab切换都有这样的效果,如联系人等,感觉效果简单实用,于是自己尝试简单实现了一下。


基本思想就是用自定义的控件来代替tabwidget,以实现效果。内容的话,可以用activityGroup来实现,或者用tabhost,然后在布局中隐藏tabwidget。


实现非常简单,代码如下:

package bbk.cly.MovableTab;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

/**
 * 主activity
 * @author cly
 */
public class MovableTabActivity extends Activity implements OnClickListener
{
	private static final String TAG = "MovableTabActivity";
	private MovableTabView mTopView;
	private FrameLayout.LayoutParams mTopViewLP;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		FrameLayout fl = new FrameLayout(this);
		fl.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

		for (int i = 0; i < 4; i++)
		{
			Button button = new Button(this);
			button.setOnClickListener(this);
			button.setText("按钮" + i);

			FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(120, 80);
			flp.leftMargin = i * 120;
			flp.gravity = Gravity.LEFT ;
			button.setLayoutParams(flp);
			fl.addView(button);
		}

		 mTopView = new MovableTabView(this);
		 mTopView.setAlpha(200);
		 mTopViewLP = new FrameLayout.LayoutParams(120, 70);
		 mTopViewLP.gravity = Gravity.LEFT ;
		 mTopView.setImageResource(R.drawable.move);
		 mTopView.setLayoutParams(mTopViewLP);
		 fl.addView(mTopView);

		setContentView(fl);
	}

	@Override
	public void onClick(View v)
	{
		final int viewLeft = v.getLeft();
		final int topViewLeft = mTopView.getLeft();
		final int delta = v.getLeft() - mTopView.getLeft();
		
		Log.d(TAG, "onClick view left: " + viewLeft + " top view left: " + topViewLeft);
		
		mTopViewLP.leftMargin = viewLeft;
		mTopView.setLP(mTopViewLP);
		TranslateAnimation ani = new TranslateAnimation(0, delta, 0, 0);
		ani.setDuration(300);
		mTopView.startAnimation(ani);
	}
}


另一个自定义控件:

package bbk.cly.MovableTab;

import android.content.Context;
import android.widget.FrameLayout;
import android.widget.ImageView;

/**
 * 写这个类的原因是因为animationlistener的onAnimationEnd函数调用较晚,在里面改变布局会导致闪烁现象。
 * @author cly
 */
public class MovableTabView extends ImageView
{
	private FrameLayout.LayoutParams mLP;
	public MovableTabView(Context context)
	{
		super(context);
	}

	public void setLP(FrameLayout.LayoutParams lp)
	{
		mLP = lp;
	}
	
	/**
	 * 这个函数里改变布局不会有闪烁现象
	 */
	@Override
	protected void onAnimationEnd()
	{
		setLayoutParams(mLP);
		super.onAnimationEnd();
	}
}

留作记录,自己好翻阅。