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

先看一下效果图

先说一下原理,“一”、“二”、“三”是三个按钮,在三个按钮下面有两个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>

源码下载

时间: 2024-08-29 01:59:03

实现颜色渐变的顶部分页栏的相关文章

ios 导航栏透明, 上下滑动 导航栏 颜色渐变

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px "PingFang SC"; color: #008400 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #3d1d81 } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400 } p.p4 {

CSS 实现背景色渐变和文字颜色渐变

1. 背景色渐变 A . linear-gradient:用线性渐变创建图像. 语法:<linear-gradient> = linear-gradient([ [ <angle> | to <side-or-corner> ] ,]? <color-stop>[, <color-stop>]+) 下述值用来表示渐变的方向,可以使用角度或者关键字来设置: <angle>:用角度值指定渐变的方向(或角度). to left: 设置渐变为

颜色渐变CSS

颜色渐变CSS IE系列 filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FF0000',endColorStr='#F9F900',gradientType='0'); 参数:startColorStr起始颜色 endColorStr结束颜色 gradientType为0时代表垂直,为1时代表水平 Firefox background: -moz-linear-gradient(top, #FF0000, #

CSS3颜色渐变模式总结

                                               CSS3颜色渐变模式总结     1.线性渐变:linear-gradient 语法:<linear-gradient> = linear-gradient([ [ <angle> | to <side-or-corner] ,]? <color-start>[, <color-end>]+) <side-or-corner> = [left |

Android之仿今日头条顶部导航栏效果

随着时间的推移现在的软件要求显示的内容越来越多,所以要在小的屏幕上能够更好的显示更多的内容,首先我们会想到底部菜单栏,但是有时候像今日头条新闻客户端要显示的内容太多,而且又想在主界面全部显示出来,所以有加了顶部导航栏. 今日头条顶部导航栏区域的主要部分是一个导航菜单.导航菜单是一组标签的集合,在新闻客户端中,每个标签标示一个新闻类别,对应下面ViewPager控件的一个分页面.当用户在ViewPager区域滑动页面时,对应的导航菜单标签也会相应的被选中,选中的标签通过一个矩形红框高亮显示,红框背

css3背景颜色渐变属性 兼容性测试基础环境为:windows系统;IE6.0+, Firefox4.0+, Chrome4.0+, Safari4.0+, Opera15.0+

css3背景颜色渐变属性 兼容性测试基础环境为:windows系统:IE6.0+, Firefox4.0+, Chrome4.0+, Safari4.0+, Opera15.0+ 语法: <linear-gradient>:linear-gradient([ <point>,]? <color-stop>[, <color-stop>]+); <point>:[ left | right ]? [ top | bottom ]? || <a

css3的背景颜色渐变@线性渐变

背景颜色渐变之线性渐变 语法形式: firefox浏览器 background:-moz-linear-gradient(position/deg,startColor,endColor); opera浏览器    background: -o-linear-gradient(position/deg,startColor,endColor); safari和chrome浏览器    background: -webkit-linear-gradient(position/deg,startCo

使用PagerSlidingTabStrip实现顶部导航栏

在开发中,我们有时会遇到顶部导航栏滑动切换页面的设计,如网易新闻.实现的方式有很多种,今天我们使用PagerSlidingTabStrip配合ViewPager实现顶部导航栏. 效果图如下. PagerSlidingTabStrip是github上的一个开源项目,项目地址如下.https://github.com/astuetz/PagerSlidingTabStrip (一)PagerSlidingTabStrip的使用 在使用之前,我们先来看一下PagerSlidingTabStrip中的自

微信小程序--仿京东UI样式顶部导航栏

我们先来看看京东的效果 分析 上端导航栏可以放置多个分类,可滑动 点击导航栏最右端按钮可以查看所有分类,同时背景模糊 内容部分右拉跳转到另外的分类 点击分类时导航栏的滑动部分自动滑动到合适的位置 我的实现 代码展示: js /** * categoryView.js - 分类页面 */ var fakeData = require('../../common/fakeData.js') Page( { data: { categories: ['全部'], currentTab: 0, scro