自定义 View

   public class CustomTextView extends TextView {

        private static final String TAG = CustomTextView.class.getSimpleName();

        public CustomTextView(Context context) {
            super(context);
        }

        public CustomTextView(Context context, AttributeSet attrs) {
            this(context, attrs, R.attr.CustomizeStyle);
        }

        public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);

            /**
             * AttributeSet set :XML 中定义的属性值,可能为 null;
             *
             * int[] attrs :目标属性值;
             *
             * dint defStyleAttr :在当前主题中有一个引用指向样式文件,这个样式文件将 TypedArray
             * 设置默认值。如果此参数为 0 则表示不进行默认值设置。
             *
             * int defStyleRes :默认的样式资源文件,只有当 defStyleAttr 为 0 或者无法在对应的主题下找到资源文件时才起作用。
             * 如果此参数为 0 则表示不进行默认设置。
             */
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView , defStyle, R.style.DefaultCustomizeStyle);
    //        TypedArray a = mContext.getTheme().obtainStyledAttributes(attrs,  R.styleable.CustomTextView , R.attr.CustomizeStyle, R.style.DefaultCustomizeStyle);
            String one = a.getString(R.styleable.Customize_attr_one);
            String two = a.getString(R.styleable.Customize_attr_two);
            String three = a.getString(R.styleable.Customize_attr_three);
            String four = a.getString(R.styleable.Customize_attr_four);
            Log.i(TAG, "one:" + one);
            Log.i(TAG, "two:" + two);
            Log.i(TAG, "three:" + three);
            Log.i(TAG, "four:" + four);
            a.recycle();
        }
    }

attrs.xml文件

    
    

        
            
            
            
            
        

        

    

styles.xml文件

    

        

        
        

        

        
    
        

    

在activity_main.xml中添加该试图

    
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >

        

    

你可能感兴趣的:(自定义 View)