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>
  • 相关阅读:
    linux下的磁盘挂载
    shell中的循环语句while
    hadoop安装和配置
    shell 命令 创建/删除 软连接 ln -s
    azkaban disable 停用部分工作流
    git dev 分支merge到master
    shell 命令 zip unzip
    git代码同步服务器代码需要注意的问题
    shell 命令 if elif else fi 用法
    python 引入本地 module
  • 原文地址:https://www.cnblogs.com/alexkn/p/8037693.html
Copyright © 2011-2022 走看看