Android实现布局控件自定义属性

时间:2023-03-09 16:09:37
Android实现布局控件自定义属性

一、自定义ViewGroup

1、onMeasure

决定内部View(子View)的宽度和高度,以及自己的宽度和高度

2、onLayout

决定子View放置的位置

3、onTouchEvent

定义动作

二、自定义属性

在实际的使用自定义Viewgroup时,经常会用到自定义控件的属性。

在res/values文件夹下建立attr.xml文件

1、书写xml文件,定义<attr>中的自定义属性,在<declare-stableable>中声明已经定义的属性

2、使用自定义的属性,在使用时添加命名空间,xmlns:ren="http://schemas.android.com/apk/res/bupt.ren.slidingmenu",然后即可以使用该属性

注:其中bupt.ren.slidingmenu是应用程序的包名,不是view所在的路径。

三、使用自定义的ViewGroup和自定义布局属性

1、自定义布局属性

attr.xml中定义如下:

<resources>
<attr name="rightPadding" format="dimension"></attr> //定义布局属性
<declare-styleable name="SlidingMenu"> //定义布局,其中name后必须跟着view的类名
<attr name="rightPadding"></attr> //声明属性
</declare-styleable>
</resources>

2、使用自定义布局属性

使用时,在main.xml定义如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ren="http://schemas.android.com/apk/res/bupt.ren.slidingmenu"
android:layout_width="match_parent"
android:layout_height="match_parent" > <bupt.ren.slidingmenu.view.SlidingMenu
android:id="@+id/id_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/img_frame_background"
ren:rightPadding="80dp" >
</bupt.ren.slidingmenu.view.SlidingMenu> </RelativeLayout>

3、自定义ViewGroup

在使用自定义属性时,需要覆写ViewGroup中有2个参数的构造方法,然后通过含有2个参数的构造方法,调用含有3个参数的构造方法。含有3个参数的构造方法负责接收自定义属性。

public SlidingMenu(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.SlidingMenu, defStyle, 0); int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.SlidingMenu_rightPadding:
mMenuRightPadding = a.getDimensionPixelSize(attr,
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, context
.getResources().getDisplayMetrics()));
break;
}
}
a.recycle(); //需要对TypeArray进行回收
}

获取自定义的属性,其中关键的步骤就是获取mMenuRightPadding这个参数,达到控制控件布局的效果。

得到mMenuRightPadding这个参数后,就可以再ViewGroup中的onMeasure的方法中对子View进行布局的操控。

1.转载注明:http://www.cnblogs.com/yuanblog/p/4439186.html

2.本文为个人笔记、心得,可能引用其它文章,所以博客只在私自范围内供大家学习参考。