zoukankan      html  css  js  c++  java
  • Android自定义View的套路

    一.自定义View的流程

    1.属性设置

    在styles.xml中设置控件属性,如果你想直接harcode可以忽略这步

        <!--name为声明的"属性集合"名,可以随便取,但是最好是设置为跟我们的View一样的名称-->
        <declare-styleable name="MyView">
            <!--声明我们的属性,名称为default_size,取值类型为尺寸类型(dp,px等)-->
            <attr name="default_size" format="dimension" />
        </declare-styleable>

    在这里关联的是View是MyView

    2.创建自定义View,跟styles.xml配置保持一致

    public class MyView extends View {
    
        private int defalutSize;
    
        public MyView(Context context) {
            super(context);
        }
    
        public MyView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
    
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
            defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100); // 获取styles.xml配置的属性,R文件名称:R.styleable+属性集合名称+下划线+属性名称
         a.recycle(); 
        }

        ... }

    3.view的显示

    假设我要在主界面显示我的view

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:hc="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="sdasdasds"/>
        <com.example.qingge.drawviewtest.MyView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            hc:default_size="100dp" />
    
    </LinearLayout>
  • 相关阅读:
    JavaScript 多个空格替换成1个空格
    「DIARY」NOI2021 小结
    kubernetes常用命令总结
    Qt绘图(使用QPainter)翻转图像的两种方法
    android 11 R framework 新特证 开发备忘
    浏览器的缓存机制
    记el-tree 懒加载复选框回显的坑
    VUE根据文件流下载EXC
    西瓜视频播放器VUE
    推荐系统打散算法--权重
  • 原文地址:https://www.cnblogs.com/alexkn/p/8037693.html
Copyright © 2011-2022 走看看