Android中自定义ViewGroup

public  void addView(View child) {

addView(child, -1);

}

这个方法是用来想View容器中添加组件用的。我们可以使用这个方法想这个ViewGroup中添加组件。

3、getChildAt方法

复制代码

public View getChildAt( int index) {

try {

return mChildren[index];

}  catch (IndexOutOfBoundsException ex) {

return  null;

}

}

复制代码

这个方法用来返回指定位置的View。外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

资料获取→专栏

注意:ViewGroup中的View是从0开始计数的。

可以说我们自定义ViewGroup时这三个方法是至关重要的,下面我们就来看看自定义ViewGroup使用。

三、一个小Demo

我们新建一个叫AndroidViewGroup的工程,Activity起名为MainActivity。在写一个继承于ViewGroup的类,名叫HelloViewGroup。

复制代码

–>HelloViewGroup类

public  class 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

protected  void onLayout( boolean changed,  int l,  int t,  int r,  int b) {

//  TODO Auto-generated method stub

}

}

复制代码

复制代码

–>MainActivity类

public  class MainActivity  extends Activity {

/**  Called when the activity is first created.  */

public  void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView( new HelloViewGroup( this));

}

}

复制代码

这时你可以运行一下,发现屏幕除了状态栏了那个Label是一片黑,呵呵。下面我们来修改代码,让自己的ViewGroup火起来。

我们新建一个名叫myAddView的方法,这个方法用来向ViewGroup中添加组件:

复制代码

/**     * 添加View的方法

*  */

public  void myAddView(){

ImageView mIcon =  new ImageView(mContext);

mIcon.setImageResource(R.drawable.haha);

addView(mIcon);

}

复制代码

然后我们修改onLayou
t方法:

@Override

protected  void onLayout( boolean changed,  int l,  int t,  int r,  int b) {

View v = getChildAt(0);
v.layout(l, t, r, b);
}
然后我们看看运行效果:

rotected  void onLayout( boolean changed,  int l,  int t,  int r,  int b) {

View v = getChildAt(0);
v.layout(l, t, r, b);
}
然后我们看看运行效果:
[外链图片转存中…(img-vOfISwlF-1718732752747)]

  • 14
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值