- package com.arui;
- import android.content.Context;
- import android.util.Log;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Button;
- /**
- * Example for using ViewGroup.
- *
- * @author http://blog.csdn.net/arui319
- * @version 2010/09/07
- *
- */
- public class MyViewGroup extends ViewGroup {
- public MyViewGroup(Context context) {
- super(context);
- this.initOtherComponent(context);
- }
- private void initOtherComponent(Context context) {
- Button aBtn = new Button(context);
- // set id 1
- aBtn.setId(1);
- aBtn.setText("a btn");
- this.addView(aBtn);
- Button bBtn = new Button(context);
- // set id 2
- bBtn.setId(2); //此处如何不设置,将显示不出来 为什么?
- bBtn.setText("b btn");
- this.addView(bBtn);
- }
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- int childCount = getChildCount();
- for (int i = 0; i < childCount; i++) {
- View child = getChildAt(i);
- switch (child.getId()) {
- case 1:
- // 1 is aBtn
- Log.d("MyViewGroup", "btn1 setting");
- child.setVisibility(View.VISIBLE);
- child.measure(r - l, b - t);
- child.layout(0, 0, child.getMeasuredWidth(), child
- .getMeasuredHeight());
- break;
- case 2:
- // 2 is bBtn
- Log.d("MyViewGroup", "btn2 setting");
- child.setVisibility(View.VISIBLE);
- child.measure(r - l, b - t);
- child.layout(0, 50, child.getMeasuredWidth(), child
- .getMeasuredHeight() + 50);
- break;
- default:
- //
- }
- }
- }
- }
viewGroup demo
最新推荐文章于 2022-03-24 19:49:44 发布