Java 如何在代码中将视图添加到线性布局的顶部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8270224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-15 00:29:09  来源:igfitidea点击:

How to add a view to the top of a linear layout in code?

javaandroidviewadmobandroid-linearlayout

提问by cody

I need to add an admob adview to a linear layout in code but I need to insert it at the top of the layout, not the bottom.

我需要在代码中将 admob adview 添加到线性布局,但我需要将其插入布局的顶部,而不是底部。

Is there a way to do this?

有没有办法做到这一点?

采纳答案by Caner

Use:

用:

public void addView (View child, int index) Since: API Level 1

Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child. Parameters child the child view to add index the position at which to add the child See Also

public void addView (View child, int index) 自:API 级别 1

添加子视图。如果尚未在 child 上设置布局参数,则在 child 上设置此 ViewGroup 的默认参数。参数 child 子视图添加 index 添加子视图的位置 另请参见

So

所以

yourLayout.addView(yourView, 0);

http://developer.android.com/reference/android/view/ViewGroup.html#addView(android.view.View,%20int)

http://developer.android.com/reference/android/view/ViewGroup.html#addView(android.view.View,%20int)

回答by Jong

I was trying to do it as well, but using only LinearLayoutit always added the view at the bottom, no matter which indexI passed to addView.

我也试图这样做,但只使用LinearLayout它总是在底部添加视图,无论index我传递给addView.

I wrapped the LinearLayoutin a RelativeLayout, then you do that:

我将 包裹LinearLayout在 a 中RelativeLayout,然后您执行以下操作:

relativeLayout.addView(adView);
adView.setId(12345678);
RelativeLayout.LayoutParams llParams = (RelativeLayout.LayoutParams)linearLayout.getLayoutParams();
llParams.addRule(RelativeLayout.BELOW, adView.getId());

That is working for me.

这对我有用。