码迷,mamicode.com
首页 > 其他好文 > 详细

实现颜色渐变的顶部分页栏

时间:2015-02-10 11:15:46      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:android   分页栏   

先看一下效果图

技术分享

先说一下原理,“一”、“二”、“三”是三个按钮,在三个按钮下面有两个TextView,一个是青色的,一个是灰色的,通过不断调整青色TextView的宽度,来达到颜色渐变的效果。按钮下面是一个ViewPager+Fragment来是滑动翻页。

这里布局文件非常重要,我先把布局文件贴出来,activity_main.xml

<RelativeLayout 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:background="@android:color/white" >

   <span style="color:#33ff33;"> <LinearLayout
        android:id="@+id/gradation_back"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/cywnText"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#99ff33" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#d3d3d3" />
    </LinearLayout></span>

    <LinearLayout
        android:id="@+id/top_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:orientation="horizontal" >
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/gradation_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/top_bar" />

</RelativeLayout>
注意青色字体的那部分代码,灰色(#d3d3d3)背景TextView的宽度是match_parent,这个是match_parent在这里并没有占据屏幕的整个宽度,因为在灰色的TextView前面定义了一个青色(#99ff33)背景的TextView,所以系统会首先要满足青色背景的TextView的宽度要求,之后剩下的屏幕宽度才会被灰色背景的TextView占满。所以我们在代码中只需要不断调整青色背景的TextView的宽度即可。

初始化控件并实现ViewPager的滑动翻页功能。

private void init() {
		// TODO Auto-generated method stub
		grabackll = (LinearLayout) findViewById(R.id.gradation_back);
		topll = (LinearLayout) findViewById(R.id.top_bar);
		cywnTxt = (TextView) findViewById(R.id.cywnText);
		graViewPager = (ViewPager) findViewById(R.id.gradation_pager);
		initFragment();
		graAdapter = new GraAdapter(getSupportFragmentManager(), fList);
		graViewPager.setAdapter(graAdapter);
		graViewPager.setOnPageChangeListener(new GraPagerChangeListener());
		graViewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				float newX;
				// 判断手指在屏幕上的滑动方向
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				case MotionEvent.ACTION_DOWN:
					oldX = event.getX();
					break;
				case MotionEvent.ACTION_MOVE:
					newX = event.getX();
					if (newX - oldX > 0)
						type = 1;
					else if (newX - oldX < 0)
						type = 0;
					break;

				}
				return false;
			}
		});
		initTopBar();
		setGraWidth(((float) screenWidth) / 3);

	}
/**
	 * 添加滑动界面,这里添加了三个界面,相应的TopBar就应该分成三部分
	 */
	private void initFragment() {
		// TODO Auto-generated method stub
		GraFragment1 f1 = new GraFragment1();
		GraFragment2 f2 = new GraFragment2();
		GraFragment3 f3 = new GraFragment3();
		fList.add(f1);
		fList.add(f2);
		fList.add(f3);
	}
private void initTopBar() {
		// 将三个按钮添加topbar
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
				LayoutParams.WRAP_CONTENT);
		params.weight = 1;
		String[] array = { "一", "二", "三" };
		for (int i = 0; i < 3; i++) {
			Button btn = new Button(this);
			btn.setBackgroundColor(Color.TRANSPARENT);
			btn.setTag(String.valueOf(i+1));
			btn.setText(array[i]);
			btn.setOnClickListener(this);
			topll.addView(btn, params);
		}
		// 设置背景色高度与topbar一致
		ViewTreeObserver vto = topll.getViewTreeObserver();
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {
				int height = topll.getMeasuredHeight();
				int width = topll.getMeasuredWidth();
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) grabackll
						.getLayoutParams();
				if (width > height) {
					params.width = width;
					params.height = width;
				} else {
					params.width = height;
					params.height = height;
				}
				grabackll.setLayoutParams(params);
				return true;
			}
		});

	}

/**
	 * 设置青色背景的TextView的宽度
	 * 
	 * @param width
	 */
	private void setGraWidth(float width) {
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) cywnTxt
				.getLayoutParams();
		params.width = (int) width;
		cywnTxt.setLayoutParams(params);
	}

private class GraPagerChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
			switch (state) {
			case ViewPager.SCROLL_STATE_DRAGGING:// 这个状态表示手指正在滑动ViewPager,为了防止连续的快速滑动导致索引值的偏差,在滑动时加载索引值
				oldindex = index;
				break;
			case ViewPager.SCROLL_STATE_IDLE:// 这个状态表示ViewPager停止滑动,滑动停止时由新的将新的索引值赋给oldindex
				oldindex = index;
				offsetX = 0;
				break;
			case ViewPager.SCROLL_STATE_SETTLING:// 这个状态表示手指不在屏幕上滑动ViewPager,但由于惯性ViewPager还在继续滑动
				break;
			}

		}

		@Override
		public void onPageScrolled(int position, float scaleDist, int dist) {
			// TODO Auto-generated method stub
			//在滑动过程中改变青色背景TextView的宽度
			if (scaleDist != 0)
				switch (type) {
				case 0:// 向右滑动
					dis = ((float) screenWidth) / 3 * scaleDist;
					setGraWidth(((float) screenWidth) / 3 * (oldindex) + dis
							+ offsetX);
					break;
				case 1:// 向左滑动
					dis = ((float) screenWidth) / 3 * (1 - scaleDist);
					setGraWidth(((float) screenWidth) / 3 * (oldindex) - dis
							- offsetX);
					break;
				}

		}

		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			index = position + 1;
			offsetX = ((float) screenWidth) / 3
					* (Math.abs(index - oldindex) - 1);
		}
	}

@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int position = graViewPager.getCurrentItem();
		int newPosition = Integer.valueOf(v.getTag().toString()) - 1;
		if (newPosition > position)
			type = 0;
		else if (newPosition < position)
			type = 1;
		graViewPager.setCurrentItem(newPosition);
	}

MainActivity完整代码

package com.example.gradationbar;

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

import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnGenericMotionListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements OnClickListener {
	private LinearLayout grabackll, topll;
	private TextView cywnTxt;
	private ViewPager graViewPager;
	private List<Fragment> fList = new ArrayList<Fragment>();
	private GraAdapter graAdapter;
	private int screenWidth;
	private int oldindex = 1, index = 1;
	private float dis;
	private static int type = 0;// 0表示向右,1表示向左
	private float oldX;
	private float offsetX = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 获取屏幕宽度
		Display dispaly = getWindowManager().getDefaultDisplay();
		screenWidth = dispaly.getWidth();
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		grabackll = (LinearLayout) findViewById(R.id.gradation_back);
		topll = (LinearLayout) findViewById(R.id.top_bar);
		cywnTxt = (TextView) findViewById(R.id.cywnText);
		graViewPager = (ViewPager) findViewById(R.id.gradation_pager);
		initFragment();
		graAdapter = new GraAdapter(getSupportFragmentManager(), fList);
		graViewPager.setAdapter(graAdapter);
		graViewPager.setOnPageChangeListener(new GraPagerChangeListener());
		graViewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				float newX;
				// 判断手指在屏幕上的滑动方向
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				case MotionEvent.ACTION_DOWN:
					oldX = event.getX();
					break;
				case MotionEvent.ACTION_MOVE:
					newX = event.getX();
					if (newX - oldX > 0)
						type = 1;
					else if (newX - oldX < 0)
						type = 0;
					break;

				}
				return false;
			}
		});
		initTopBar();
		setGraWidth(((float) screenWidth) / 3);

	}

	/**
	 * 添加滑动界面,这里添加了三个界面,相应的TopBar就应该分成三部分
	 */
	private void initFragment() {
		// TODO Auto-generated method stub
		GraFragment1 f1 = new GraFragment1();
		GraFragment2 f2 = new GraFragment2();
		GraFragment3 f3 = new GraFragment3();
		fList.add(f1);
		fList.add(f2);
		fList.add(f3);
	}

	private void initTopBar() {
		// 将三个按钮添加topbar
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
				LayoutParams.WRAP_CONTENT);
		params.weight = 1;
		String[] array = { "一", "二", "三" };
		for (int i = 0; i < 3; i++) {
			Button btn = new Button(this);
			btn.setBackgroundColor(Color.TRANSPARENT);
			btn.setTag(String.valueOf(i + 1));
			btn.setText(array[i]);
			btn.setOnClickListener(this);
			topll.addView(btn, params);
		}
		// 设置背景色高度与topbar一致
		ViewTreeObserver vto = topll.getViewTreeObserver();
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {
				int height = topll.getMeasuredHeight();
				int width = topll.getMeasuredWidth();
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) grabackll
						.getLayoutParams();
				if (width > height) {
					params.width = width;
					params.height = width;
				} else {
					params.width = height;
					params.height = height;
				}
				grabackll.setLayoutParams(params);
				return true;
			}
		});

	}

	/**
	 * 设置青色背景的TextView的宽度
	 * 
	 * @param width
	 */
	private void setGraWidth(float width) {
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) cywnTxt
				.getLayoutParams();
		params.width = (int) width;
		cywnTxt.setLayoutParams(params);
	}

	private class GraPagerChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
			switch (state) {
			case ViewPager.SCROLL_STATE_DRAGGING:// 这个状态表示手指正在滑动ViewPager,为了防止连续的快速滑动导致索引值的偏差,在滑动时加载索引值
				oldindex = index;
				break;
			case ViewPager.SCROLL_STATE_IDLE:// 这个状态表示ViewPager停止滑动,滑动停止时由新的将新的索引值赋给oldindex
				oldindex = index;
				offsetX = 0;
				break;
			case ViewPager.SCROLL_STATE_SETTLING:// 这个状态表示手指不在屏幕上滑动ViewPager,但由于惯性ViewPager还在继续滑动
				break;
			}

		}

		@Override
		public void onPageScrolled(int position, float scaleDist, int dist) {
			// TODO Auto-generated method stub
			//在滑动过程中改变青色背景TextView的宽度
			if (scaleDist != 0)
				switch (type) {
				case 0:// 向右滑动
					dis = ((float) screenWidth) / 3 * scaleDist;
					setGraWidth(((float) screenWidth) / 3 * (oldindex) + dis
							+ offsetX);
					break;
				case 1:// 向左滑动
					dis = ((float) screenWidth) / 3 * (1 - scaleDist);
					setGraWidth(((float) screenWidth) / 3 * (oldindex) - dis
							- offsetX);
					break;
				}

		}

		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			index = position + 1;
			offsetX = ((float) screenWidth) / 3
					* (Math.abs(index - oldindex) - 1);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int position = graViewPager.getCurrentItem();
		int newPosition = Integer.valueOf(v.getTag().toString()) - 1;
		if (newPosition > position)
			type = 0;
		else if (newPosition < position)
			type = 1;
		graViewPager.setCurrentItem(newPosition);
	}

}
GraAdapter

package com.example.gradationbar;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class GraAdapter extends FragmentPagerAdapter {
	private List<Fragment> fList;

	public GraAdapter(FragmentManager fm, List<Fragment> fList) {
		super(fm);
		this.fList = fList;
		// TODO Auto-generated constructor stub
	}

	@Override
	public Fragment getItem(int arg0) {
		// TODO Auto-generated method stub
		return fList == null ? null : fList.get(arg0);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return fList == null ? -1 : fList.size();
	}

}

GraFragment1

package com.example.gradationbar;

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 GraFragment1 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_gra, null);
		TextView graTxt = (TextView) view.findViewById(R.id.fragment_gra);
		graTxt.setText("我是第一个界面");
		return view;
	}

}
GraFragment2

package com.example.gradationbar;

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 GraFragment2 extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_gra, null);
		TextView graTxt = (TextView) view.findViewById(R.id.fragment_gra);
		graTxt.setText("我是第二个界面");
		return view;
	}
}
GraFragment3

package com.example.gradationbar;

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 GraFragment3 extends Fragment{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_gra, null);
		TextView graTxt = (TextView) view.findViewById(R.id.fragment_gra);
		graTxt.setText("我是第三个界面");
		return view;
	}
}
fragment_gra.xml

<RelativeLayout 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:background="@android:color/white" >

    <TextView
        android:id="@+id/fragment_gra"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

</RelativeLayout>

源码下载









实现颜色渐变的顶部分页栏

标签:android   分页栏   

原文地址:http://blog.csdn.net/qmln31821007/article/details/43700151

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!