第一步、在res/value中创建一个attrs.xml文件
<?xml version="1.0" encoding="utf-8"?><resources><!-- format 是表示在Android中的数据类型 --><declare-styleable name="MyTextView"><attr format="color" name="readLineColor"></attr><attr format="dimension" name="readLineSize"></attr><attr format="string" name="readLineText"></attr><attr name="weight"><flag name="fat" value="2" /><flag name="mid" value="1" /><flag name="thin" value="0" /></attr></declare-styleable></resources>
第二步、编写自定义TextView,MyTextView类
public class MyTextView extends TextView {private Context context;public MyTextView(Context context, AttributeSet attrs) {super(context, attrs);this.context = context;TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);//获取每一个属性的值int textColor = attributes.getColor(R.styleable.MyTextView_readLineColor, 0XFFFFFF);float textSize = attributes.getDimension(R.styleable.MyTextView_readLineSize, 24);String text = attributes.getString(R.styleable.MyTextView_readLineText);//获取flag中的属性值int weight = attributes.getInt(R.styleable.MyTextView_weight, 1);setWeightStatus(weight);if(text == null || text.length() == 0){text = "null";}attributes.recycle();//把属性添加到TextView中setText(text);setTextColor(textColor);setTextSize(textSize);}private void setWeightStatus(int weight) {switch (weight) {case 0:Toast.makeText(context, "一般般", 0).show();break;case 1:Toast.makeText(context, "中等", 0).show();break;case 2:Toast.makeText(context, "优秀", 0).show();break;}}}
第三步、最重要的一部,很多地方需要注意。
定义规则信息:一般按照xmls:android中的内容进行编写,如下自定义方式:
xmlns:mytext="
http://schemas.android.com/apk/res/
com.sen5.textview.demo
"
上面这个分为两步:
第一步:mytext 自定义名称,任意字符
第二步:
http://schemas.android.com/apk/res/
前面这个是一个URL地址,可以写你们的公司网站,后面的
com.textview.demo
后面的这个必须是该应用程序的package名,否则找不到内容,下面的属性就可以直接对应attrs中对应的方法了。如下
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:mytext="http://schemas.android.com/apk/res/com.textview.demo"android:layout_width="match_parent"android:layout_height="match_parent" ><com.sen5.textview.demo.view.MyTextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"mytext:readLineColor="#000000"mytext:readLineSize="28sp"mytext:readLineText="我要找个女朋友"mytext:weight="fat"/></RelativeLayout>
还有一种方式可以获取自定义中的属性,就是通过
AttributeSet
attrs里面的方法如
//根据命名空间的方式获取namespace标示你定义的http://schemas.android.com/apk/res/com.textview.demoattribute表示你定义的declare-styleable定义的name值attrs.getAttributeBooleanValue(namespace, attribute, defaultValue)
本文介绍如何在Android中创建自定义TextView,并详细说明了从定义属性到实现类的过程,包括使用XML声明样式及在布局文件中引用这些样式。
863

被折叠的 条评论
为什么被折叠?



