自定义shape的view,不用配置xml

使用shape作为view的背景很灵活,一般可以通过创建XML来实现,但是如果样式过多,那么相应的xml文件也多,不好维护,这里介绍使用代码在创建shape背景,个人感觉很方便

以TextView为例

public class ShapeTextView extends TextView
{
private Context context;


private GradientDrawable gradientDrawable;


/**
* @param context
* @param attrs
*/
public ShapeTextView(Context context,AttributeSet attrs)
{
super(context,attrs);
this.context = context;
gradientDrawable = new GradientDrawable();
}


public GradientDrawable getGradientDrawable()
{
return gradientDrawable;
}


/**
* 设置背景色
*
* @param color
*/
@SuppressWarnings("deprecation")
public void setColor(int color)
{
gradientDrawable.setColor(color);
setBackgroundDrawable(gradientDrawable);
}


/**
* 设置圆角弧度
*
* @param radius
*/
@SuppressWarnings("deprecation")
public void setCornerRadius(float radius)
{
gradientDrawable.setCornerRadius(radius);
setBackgroundDrawable(gradientDrawable);
}


/**
* 设置边框宽度和颜色
*
* @param width
* @param color
*/
@SuppressWarnings("deprecation")
public void setstroke(int width,int color)
{
gradientDrawable.setstroke(width,color);
setBackgroundDrawable(gradientDrawable);
}


/**
* 设置背景样式
*
* @param bgcolor
* 背景颜色
* @param radius
* 圆角弧度
* @param strokewidth
* 边框宽度
* @param strokecolor
* 边框颜色
*/
@SuppressWarnings("deprecation")
public void setShape(int bgcolor,float radius,int strokewidth,
int strokecolor)
{
gradientDrawable.setColor(bgcolor);
gradientDrawable.setCornerRadius(radius);
gradientDrawable.setstroke(strokewidth,strokecolor);
setBackgroundDrawable(gradientDrawable);
}
}

主要通过构建GradientDrawable,并设置背景颜色、圆角弧度、边框宽度,边框颜色等属性

代码很简单,样式都能看懂

其他类型的源码(包括通过代码设置属性自定义属性,并在xml中配置)

http://download.csdn.net/detail/dianqiugg/6755919

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念