Android之在Layout中自定义View

在Layout中自定义View

经常会看到在XML文件中调用别人的View就可以显示出各种奇妙的页面

简单的学习了一下,下面说一下如何自定义一个View, 并设置背景色

 
 
  1. // 第一步,创建一个继承自View的类
  2. public class MyView extends View {
  3. // 背景颜色
  4. private int background;
  5. // 默认背景颜色
  6. private final int default_background = Color.rgb(66, 145, 241);
  7. // 构造
  8. public MyView(Context context) {
  9. // 这里确保每一级都会被触发
  10. this(context, null);
  11. }
  12. // 构造
  13. public MyView(Context context, AttributeSet attrs) {
  14. // 这里确保每一级都会被触发
  15. this(context, attrs, R.attr.MyViewStyle);
  16. }
  17. // 构造
  18. public MyView(Context context, AttributeSet attrs, int defStyle) {
  19. // 执行父类构造
  20. super(context, attrs, defStyle);
  21. // 初始化
  22. final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
  23. // 获取设置的背景颜色
  24. background = attributes.getColor(R.styleable.MyView_background, default_background);
  25. // 设置
  26. this.setBackgroundColor(background);
  27. }
  28. }

 
 
  1. // 第二步,在XML-Layout中使用
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@drawable/guide_0"
  8. android:orientation="vertical">
  9. // 这里使用的就是自定义的View
  10. <com.example.nljb.surpass.MyView
  11. // 可以使用自定义的View的设置参数
  12. app:background="#ffff5633"
  13. // 可以使用继承自View的设置参数
  14. android:layout_width="match_parent"
  15. android:layout_height="50dp"/>
  16. </RelativeLayout>

 
 
  1. // 第三步,自定义View的参数(第一步已经讲了如何使用)
  2. // values/attrs
  3. <?xml version="1.0" encoding="utf-8"?>
  4. <resources>
  5. <declare-styleable name="MyView">
  6. // format 类型有很多 ...
  7. <attr name="background" format="color"/>
  8. // <attr name="..." format="integer"/>
  9. // <attr name="..." format="dimension"/>
  10. // <attr name="..." format="enum">
  11. // <enum name="..." value="0"/>
  12. // <enum name="..." value="1"/>
  13. // </attr>
  14. // <attr name="..." format="string"/>
  15. // <attr name="..." format="boolean"/>
  16. ...
  17. </declare-styleable>
  18. <declare-styleable name="Themes">
  19. <attr name="MyViewStyle" format="reference"/>
  20. </declare-styleable>
  21. </resources>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值