Android自定义控件之TextView
来源:互联网 发布:linux下载迅雷资源 编辑:程序博客网 时间:2024/05/16 18:33
有时候Android自带的控件无法满足我们的某些要求,这时就需要我们自定义控件来实现这些功能。比如需要一个TextView里的字倾斜一定的角度,就需要自定义TextView。
下面介绍怎么自定义TextView。
首先新建一个继承自TextView的类,取名为RotateTextView:
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
public class RotateTextView extends TextView {
private static final String NAMESPACE = “http://www.ywlx.net/apk/res/easymobi”;
private static final String ATTR_ROTATE = “rotate”;
private static final int DEFAULTVALUE_DEGREES = 0;
private int degrees ;
public RotateTextView(Context context, AttributeSet attrs) {
super(context, attrs);
degrees = attrs.getAttributeIntValue(NAMESPACE, ATTR_ROTATE, DEFAULTVALUE_DEGREES);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.rotate(degrees,getMeasuredWidth()/2,getMeasuredHeight()/2);
super.onDraw(canvas);
}
}
一定要有带Context和AttributeSet参数的构造函数,getAttributeIntValue()里第一个参数是命名空间,类似于Android自带的”http://schemas.android.com/apk/res/android”,这里可以自己随便定义。第二个参数是传入的参数的值,这里是旋转地角度。第三个参数是默认值,就是不定义该属性时默认旋转的角度,这里是0度。然后重写onDraw()方法,rotate()作用是以TextView的中心为中点把画布旋转degrees度,这样就实现了字的旋转。
下一步就是在布局文件中使用自定义的TextView:
<cn.easymobi.application.memorytest.RotateTextViewandroid:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:padding=”8dip”
android:gravity=”center”
android:id=”@+id/tvBottom_color”
android:textSize=”15dip”
android:textColor=”@color/black”easymobi:rotate=”10″
android:layout_marginTop=”468dip”
/>
其他属性与普通的TextView相同, easymobi:rotate=”10″指定了旋转10度,但是要注意在头文件加上xmlns:easymobi=”http://www.ywlx.net/apk/res/easymobi”,这个就是RotateTextView中的命名空间的作用。还有一点要注意的就是加上合适的padding,因为这种方法旋转的是TextView里面的字,而不是TextView本身,如果不加padding,有些字就会因为旋转而跑到了TextView外面而不能显示。
用类似的方法还可以实现各种各样你想要的效果。
- Android自定义控件之TextView
- Android自定义控件之TextView
- Android自定义控件之TextView
- Android自定义控件之extends textview
- Android自定义控件之拓展TextView(ExpandTextView)
- Android-自定义控件之重写控件(自定义TextView)
- Android自定义TextView控件
- [android自定义控件]之自定义TextView实现两个text
- Android自定义控件之《自定义TextView(支持显示图片)》
- android控件之Textview
- android控件之TextView
- Android控件之TextView
- Android控件之Textview
- Android控件之TextView
- Android控件之Textview
- android控件之TextView
- Android控件之TextView
- Android之TextView(控件)
- 【问题】使用GCC编译c++程序遇到的protected继承问题
- 我就是我
- Procedural generated mesh in Unity: Part 1
- Windows下用Eclipse搭建C/C++开发环境
- LeetCode | String to Integer (atoi)
- Android自定义控件之TextView
- 第11章 使用结构化命令
- Java类加载原理
- How to Spend the First 10 Minutes of Your Day
- Switching From Windows to Nix or a Newbie to Linux – 20 Useful Commands for Linux Newbies
- c指针
- 面试中常见递归题目 Java版
- juanjuan
- JS判断元素为数字的奇异写法分享 这是在阅读underscore(1.3.3)源码中看到的,它的each方法