近段时间在研究launcher源码,从中也学习到不到新东西,这次是自定义属性的使用
需要介绍的是关于自定义属性的的三个文件。文件如下:
1, /res/values/attrs.xml,代码如下
<declare-styleable name="CellLayout"> //申明一个属性的名字,一般为需要自定义属性的类名
<!-- The width of a single cell -->
<attr name="cellWidth" format="dimension" />
<!-- The height of a single cell -->
<attr name="cellHeight" format="dimension" />
<!-- Padding to apply at the start of the long axis -->
<attr name="longAxisStartPadding" format="dimension" />
<!-- Padding to apply at the end of the long axis -->
<attr name="longAxisEndPadding" format="dimension" />
<!-- Padding to apply at the start of the short axis -->
<attr name="shortAxisStartPadding" format="dimension" />
<!-- Padding to apply at the end of the short axis -->
<attr name="shortAxisEndPadding" format="dimension" />
<!-- Number of cells on the short axis of the CellLayout -->
<attr name="shortAxisCells" format="integer" />
<!-- Number of cells on the long axis of the CellLayout -->
<attr name="longAxisCells" format="integer" />
</declare-styleable>
2, /res/layout-port/workspace_screen.xml,代码如下
<com.android.launcher2.CellLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:launcher=http://schemas.android.com/apk/res/com.android.launcher2
//此处定义一个自定义属性launcher,com.android.launcher2为包名,与使用它的包名一致
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hapticFeedbackEnabled="false"
launcher:cellWidth="@dimen/workspace_cell_width"
launcher:cellHeight="@dimen/workspace_cell_height"
launcher:longAxisStartPadding="8dip"
launcher:longAxisEndPadding="78dip"
launcher:shortAxisStartPadding="0dip"
launcher:shortAxisEndPadding="0dip"
launcher:shortAxisCells="4"
launcher:longAxisCells="4" />
3,src/com/android/launcher2/CellLayout.java 代码如下
public CellLayout(Context context) {
this(context, null);
}
public CellLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CellLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
//通过TypedArray拿到CellLayout配置的属性
mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
//此处10为默认值,为了防止在xml文件中为定义
mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
mLongAxisStartPadding =
a.getDimensionPixelSize(R.styleable.CellLayout_longAxisStartPadding, 10);
mLongAxisEndPadding =
a.getDimensionPixelSize(R.styleable.CellLayout_longAxisEndPadding, 10);
mShortAxisStartPadding =
a.getDimensionPixelSize(R.styleable.CellLayout_shortAxisStartPadding, 10);
mShortAxisEndPadding =
a.getDimensionPixelSize(R.styleable.CellLayout_shortAxisEndPadding, 10);
mShortAxisCells = a.getInt(R.styleable.CellLayout_shortAxisCells, 4);
mLongAxisCells = a.getInt(R.styleable.CellLayout_longAxisCells, 4);
//最后需要调用recycle()方法,为了使先前的检索StyledAttributes回馈,便于以后的重新使用。
a.recycle();
//此处所定义的全局变量下面都会使用到,这里就不说明了。
........ }
只要对应的设置这三个文件就可以使用自定义的属性