在Android中,可以自定义类,继承ViewGroup等容器类,以实现自己需要的布局显示。

来源:互联网 发布:23周胎儿发育标准数据 编辑:程序博客网 时间:2024/04/28 03:49

在Android中,可以自定义类,继承ViewGroup等容器类,以实现自己需要的布局显示。

 

如果你在ViewGroup中增加了控件,却无法显示出来,那么下面这个例子,就可以用来参考了。

 

(主要是要实现onLayout()方法,在这个方法中,对每个子控件进行measure(),然后再布局。)

 

[java] view plaincopyprint?
  1. package com.arui;  
  2. import android.content.Context;  
  3. import android.util.Log;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6. import android.widget.Button;  
  7. /** 
  8.  * Example for using ViewGroup. 
  9.  *  
  10.  * @author http://blog.csdn.net/arui319 
  11.  * @version 2010/09/07 
  12.  * 
  13.  */  
  14. public class MyViewGroup extends ViewGroup {  
  15.     public MyViewGroup(Context context) {  
  16.         super(context);  
  17.         this.initOtherComponent(context);  
  18.     }  
  19.     private void initOtherComponent(Context context) {  
  20.         Button aBtn = new Button(context);  
  21.         // set id 1   
  22.         aBtn.setId(1);  
  23.         aBtn.setText("a btn");  
  24.         this.addView(aBtn);  
  25.         Button bBtn = new Button(context);  
  26.         // set id 2   
  27.         bBtn.setId(2);  
  28.         bBtn.setText("b btn");  
  29.         this.addView(bBtn);  
  30.     }  
  31.     @Override  
  32.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  33.         int childCount = getChildCount();  
  34.         for (int i = 0; i < childCount; i++) {  
  35.             View child = getChildAt(i);  
  36.             switch (child.getId()) {  
  37.             case 1:  
  38.                 // 1 is aBtn   
  39.                 Log.d("MyViewGroup", "btn1 setting");  
  40.                 child.setVisibility(View.VISIBLE);  
  41.                 child.measure(r - l, b - t);  
  42.                 child.layout(0, 0, child.getMeasuredWidth(), child  
  43.                         .getMeasuredHeight());  
  44.                 break;  
  45.             case 2:  
  46.                 // 2 is bBtn   
  47.                 Log.d("MyViewGroup", "btn2 setting");  
  48.                 child.setVisibility(View.VISIBLE);  
  49.                 child.measure(r - l, b - t);  
  50.                 child.layout(0, 50, child.getMeasuredWidth(), child  
  51.                         .getMeasuredHeight() + 50);  
  52.                 break;  
  53.             default:  
  54.                 //   
  55.             }  
  56.         }  
  57.     }  
  58. }