一个有趣的应用:xml+class自定义属性前缀

首先android textview的粗体效果对于汉字不知道为什么的没用用处 设置了也没什么变化,然则这只对英文有效,当你的TextView要显示中文的时辰要在code中设置粗体的paint来实现,如下
TextViewtitle=newTextView(context);TextPaintpaint=title.getPaint();
paint.setFakeBoldText(true);
还有从xml中得到,但是这样麻烦在我项目中有很多次,我必须设置一个ID然后去找到,然后再去用代码设置它的大小,所以我想了一个一劳用逸的方法,那就是自定view,但我也不知道自定view怎么弄,所以有如下:
在贴出代码之前首先就view的重点说一下:
1. 如果含有自己独特的属性,那么就需要在构造函数中获取属性文件attrs.xml中自定义属性的名称 并根据需要设定默认值,
2.如果使用自定义属性,那么在应用xml文件中需要加上新的schemas,
比如这里 xmlns:my=" http://schemas.android.com/apk/res/demo.dedo",
3.其中xmlns后的“my”是自定义的属性的前缀,res后的是我们自定义View所在的包
4.特别注意,因为我在我编写的时候,老是出现,找不到资源什么什么的,我看了一下,“自定义View所在的包”必须和AndroidManifest中的 package="demo.dedo"相同。

1.attrs.xml
[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3. declare-styleablename="TestView">
  4. attrname="textblod"format="integer"/>
  5. </declare-styleable>

2.TestView
[java] view plain copy
  1. packagedemo.dedo;
  2. importandroid.content.Context;
  3. importandroid.content.res.TypedArray;
  4. importandroid.text.TextPaint;
  5. importandroid.util.AttributeSet;
  6. importandroid.widget.TextView;
  7. publicclassTestViewextendsTextView
  8. {
  9. privateTextPaintpaint;
  10. privateContextmContext;
  11. publicTestView(Contextcontext,AttributeSetattrs)
  12. super(context,attrs);
  13. //TODOAuto-generatedconstructorstub
  14. mContext=context;
  15. //对于我们自定义的类中,我们需要使用一个名为obtainStyledAttributes的方法来获取我们的定义
  16. TypedArrayparams=mContext.obtainStyledAttributes(attrs,
  17. R.styleable.TestView);
  18. //得到自定义控件的属性值。
  19. intbackgroundId=params.getInteger(R.styleable.TestView_textblod,0);
  20. setTextblod(backgroundId);
  21. }
  22. voidsetTextblod(inttextblod)
  23. if(textblod==1)
  24. paint=super.getPaint();
  25. paint.setFakeBoldText(true);
  26. }
  27. }

3.在xml中引用view
copy
    <?xmlversion="1.0"encoding="utf-8"?>
  1. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:my="http://schemas.android.com/apk/res/demo.dedo"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <deme.deme.TestView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. my:textblod="1"
  11. android:text="这只是一个测试"
  12. />
  13. </LinearLayout>

相关文章

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