又翻开一个新篇章了,哈哈,上一回学习的是继承
View
,关于继承
View
个人感觉不是那么完美,做技术的总是想让一切完美,但世界上本就没有完美,由他吧。这回研究的是
ViewGroup
。说实话,个人感觉这个类的功能还是很强大的,这里我们只给出最基本的东西,好了,继续开始研究吧,,路漫漫其修远兮,吾将上下而求索。
一、ViewGroup概述
研究
ViewGroup
之前,我们先来看看
ViewGroup
的介绍:
|
/**
*
A
ViewGroup
is
a
special
view
that
can
contain
other
views
*
(called
children.)
The
view
group
is
the
base
class
for
layouts
and
views
*
containers.
This
class
also
defines
the
*
android.view.ViewGroup
.LayoutParams
class
which
serves
as
the
base
*
class
for
layouts
parameters.
|
|
一个
ViewGroup
是一个可以包含其他
view
的特别的
View
,
ViewGroup
是各个
Layout
和
View
组件的基类,这个类还定义了
LayoutParams
类来指定这个基类的布局参数。(翻译的不太好,能看懂就行了)
|
Android
关于
ViewGroup
的解释还是比较清楚的,通过这个我们可以看出几点:
1
、
ViewGroup
是一个容器,而这个容器是继承与
View
的。
2
、
ViewGroup
是一个基类,并且是
Layout
和一些
View
组件的基类。
等等,不一而足,眼界有多高相信看到的就有多远,呵呵。
二、ViewGroup的三个方法
在继承
ViewGroup
时有三个重要的方法,下面我们就来看看:
1、onLayout方法
protectedvoid
onLayout(
boolean
changed,
int
left,
int
top,
int
right,
int
bottom) {
}
在我们继承
ViewGroup
时会在除了构造函数之外提供这个方法,我们可以看到,在
ViewGroup
的源代码中方法是这样定义的,也就是父类没有提供方法的内容,需要我们自己实现。
这个是我们布局的时候用的,待会我们就会使用到这个。
2、addView方法
publicvoid
addView(View child) {
addView(child, -1);
}
这个方法是用来想
View
容器中添加组件用的。我们可以使用这个方法想这个
ViewGroup
中添加组件。
3、getChildAt方法
public
View getChildAt(
int
index) {
try
{
return
mChildren
[index];
}
catch
(IndexOutOfBoundsException ex) {
returnnull
;
}
}
这个方法用来返回指定位置的
View
。
注意:
ViewGroup
中的
View
是从
0
开始计数的。
可以说我们自定义ViewGroup时这三个方法是至关重要的,下面我们就来看看自定义ViewGroup使用。
三、一个小Demo
我们新建一个叫
AndroidViewGroup
的工程,
Activity
起名为
MainActivity
。在写一个继承于
ViewGroup
的类,名叫
HelloViewGroup
。
HelloViewGroup
类
|
publicclass
HelloViewGroup
extends
ViewGroup {
public
HelloViewGroup(Context context, AttributeSet attrs) {
super
(context, attrs);
//
TODO
Auto-generated constructor stub
}
public
HelloViewGroup(Context context) {
super
(context);
//
TODO
Auto-generated constructor stub
}
@Override
protectedvoid
onLayout(
boolean
changed,
int
l,
int
t,
int
r,
int
b) {
//
TODO
Auto-generated method stub
}
}
|
MainActivity
类
|
publicclass
MainActivity
extends
Activity {
/**
Called
when
the
activity
is
first
created.
*/
publicvoid
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(
new
HelloViewGroup(
this
));
}
}
|
这
时你可以运行一下,发现屏幕除了状态栏了那个
Label
是一片黑,呵呵。下面我们来修改代码,让自己的
ViewGroup
火起来。
我们新建一个名叫
myAddView
的方法,这个方法用来向
ViewGroup
中添加组件:
|
/**
*
添加
View
的方法
*
*/
publicvoid
myAddView(){
ImageView mIcon =
new
ImageView(
mContext
);
mIcon.setImageResource(R.drawable.
haha
);
addView(mIcon);
}
|
然后我们修改
onLayout
方法:
|
@Override
protectedvoid
onLayout(
boolean
changed,
int
l,
int
t,
int
r,
int
b) {
View v = getChildAt(0);
v.layout(l, t, r, b);
}
|
然后我们 看看运行效果:
是不是出效果了,哈哈,自己试一试吧,不过是之前记得创建一个
mContext
并在构造函数里初始化一下。
为了更好的交流Android,可以加群:194803269 Android研究交流群① 加群时请注明:Android深入研究,并修改群昵称

5794

被折叠的 条评论
为什么被折叠?



