您的位置:首页 > 移动开发 > Android开发

shape文件用法一:在Android中,用XML文件来设置颜色的渐变

2014-04-30 14:50 781 查看
需求:要完成颜色的渐变。

做法:使用 xml文件,结合 shape完成

————————————————————————————————————————————

设置颜色的渐变,可以通过res/drawable里定义的一个xml 完成,如:/TestColor/res/drawable/color_shape.xml

写法儿如下:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 
    	startColor : 设置渐变颜色的开始值
    	endColor: 设置渐变颜色的结束值
    	
    	angle : 设置渐变的角度
    		90 :从下往上开始渐变
    		0 :从左往右开始渐变
     -->
    <gradient 
        android:startColor="#FFF"
        android:endColor="#030"
        android:angle="90"   
        />

</shape>


shape是用来定义形状的,gradient定义该形状里面为渐变色填充,startColor起始颜色,endColor结束颜色,angle表示方向角度。当angle=0时,渐变色是从左向右。 然后逆时针方向转,当angle=90时为从下往上。



Shape文件实现颜色渐变在项目中的使用方法:



实现过程:



第一步:在 res/drawable/目录下定义 xml文件:

/TestColor/res/drawable/color_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 
    	startColor : 设置渐变颜色的开始值
    	endColor: 设置渐变颜色的结束值
    	
    	angle : 设置渐变的角度
    		90 :从下往上开始渐变
    		0 :从左往右开始渐变
     -->
    <gradient 
        android:startColor="#FFF"
        android:endColor="#030"
        android:angle="90"   
        />

</shape>


第二步:在项目布局文件中,加入引用/TestColor/res/layout/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="@drawable/color_shape"
    
    tools:context=".MainActivity" >
    
</RelativeLayout>


第三步:在代码中调用 activity_main 即可:

package com.zhangeng.testcolor;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


这便是一个完整的,使用 shape 完成控制颜色渐变的实例。

效果图 如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐