自定义控件——自定义属性

当我们自定义组件时,除了可以使用android系统为我们提供好的属性之外,还可以自定义属性。自定义属性主要步骤如下:

     第一步:

      在res/values目录下新建attrs.xml文件,然后在attrs.xml文件中声明属性。

      例如:

      这里我们定义了3个自定义属性maxRow,maxColumn和orientation。

     Android支持如下10种属性:

     - - - - - - - - - - - - - - - - - - - - - - - - - - - -

     第二步:

在使用控件的布局文件中先声明自定义属性xmlns:androidshuai="http://schemas.android.com/apk/res-auto"

然后给自定义属性赋值其中androidshuai可以取任意名字

      例:

    xmlns:androidshuai="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="#ffffff">


  android:layout_width="match_parent"
  android:layout_height="match_parent"
  androidshuai:maxRow="2"
          androidshuai:orientation="vertical" />

     第四步:

      在自定义控件MyView的public MyView (Context context, AttributeSet attrs)的构造函数中获取自定义属性:

          1.TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SquareLayout2); 2.maxRow = typedArray.getInt(R.styleable.SquareLayout2_maxRow,DEFAULT_MAX_ROW); maxColumn = typedArray.getInt(R.styleable.SquareLayout2_maxColumn,DEFAULT_MAX_COLUMN); mOrientation = typedArray.getInt(R.styleable.SquareLayout2_orientation,ORIENTATION_HORIZONTAL);

maxRow,maxColumn,mOrientation都是成员变量。

  

      

 

你可能感兴趣的:(Android学习心得)