android 自定义textview属性配置

第一步、在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.MyTextView
android: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.demo
attribute表示你定义的declare-styleable定义的name
attrs.getAttributeBooleanValue(namespace, attribute, defaultValue)




猜你喜欢

转载自blog.csdn.net/bianjiyuyan/article/details/41083751