2011-12-06 15 views
6

我想创建一个自定义的ViewGroup,并且我想将它用于全屏应用程序。我正在使用“requestWindowFeature(Window.FEATURE_NO_TITLE)”来隐藏标题栏。标题栏未显示,但它仍然占用窗口顶部的空间。Android:使用FEATURE_NO_TITLE和自定义ViewGroup在窗口顶部留下空间

Here is a picture of the problem

上面用下面的代码生成的图像:

public class CustomLayoutTestActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     Button b = new Button(this); 
     b.setText("Hello"); 
     CustomLayout layout = new CustomLayout(this); 
     layout.addView(b); 
     setContentView(layout); 
    } 
} 

public class CustomLayout extends ViewGroup { 
    public CustomLayout(Context context) { 
     super(context); 
    } 
    public CustomLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 
    public CustomLayout(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 
    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) { 
     Log.i("CustomLayout", "changed="+changed+" l="+l+" t="+t+" r="+r+" b="+b); 
     final int childCount = getChildCount(); 
     for (int i = 0; i < childCount; ++i) { 
      final View v = getChildAt(i); 
      v.layout(l, t, r, b); 
     } 
    } 
} 

The full Eclipse project is here

有趣的是看到,它是给这个空间,为Android的我自定义布局。我将CustomLayout设置为我的Activity的根布局。在登录中,“onLayout”正在接收“t = 25”,这就是推动我的布局。我不知道的是我做错了什么让Android成为“t = 25”(这正是标题栏的高度)。

我在Android SDK 2.1中运行此代码,但我也发生在Android 2.2中。


编辑:如果我改变CustomLayout类的一些默认布局(如LinearLayout中),空间消失。当然,Android SDK的默认布局不会创建我尝试创建的布局,所以这就是我创建布局的原因。

尽管我创建的布局有些复杂,但这是我可以创建的最小代码,用于重现我的布局问题。

回答

3

这不是一个完整的答案,但在此期间,你可以通过在<FrameLayout />

而且包装您的自定义布局解决问题,这是值得注意的是,你的布局超出屏幕的底部。它被标题栏高度向下移动(在我的模拟器中为38像素)

编辑:明白了。 onLayout()(和相应的layout()方法)指定坐标不相对于屏幕原点,它们相对于父级(http://developer.android.com/reference/android/view/View.html#layout%28int,%20int,%20int,%20int%29)。所以系统告诉你,你处于相对坐标(0,38),并且在将它传递给你的孩子时添加它,这意味着你说你的孩子在屏幕坐标(0, 76),造成了差距。

你真正想要做的是:

v.layout(0, 0, r - l, b - t); 

这将会把你的观点的左上角对准你的孩子意见,以相同的宽度和高度为你的看法。

+0

固定它,谢谢@Hounshell。我错过了关于坐标系相对于父母的文档中的这一点。这是我想达到的结果(评论结果):[link](http://i.imgur.com/FIOIG) – lgfischer

0

我有一个FrameLayout同样的问题在2.2

我加入android:layout_gravity="top"FrameLayout