Android 如何以编程方式向视图添加视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2395769/
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-20 05:42:21  来源:igfitidea点击:

How to Programmatically Add Views to Views

android

提问by Moki

Let's say I have a LinearLayout, and I want to add a View to it, in my program from the Java code. What method is used for this? I'm not asking how it's done in XML, which I do know, but rather, how can I do something along the lines of this sample code?

假设我有一个LinearLayout,我想在我的程序中从 Java 代码添加一个视图。为此使用什么方法?我不是在问它是如何在 XML 中完成的,我知道这一点,而是我如何按照此示例代码的方式做一些事情?

(One View).add(Another View)

Like one can do in Swing.

就像在 Swing 中可以做到的那样。

回答by Brian Cooley

Calling addViewis the correct answer, but you need to do a little more than that to get it to work.

打电话addView是正确的答案,但你需要做更多的事情才能让它发挥作用。

If you create a View via a constructor (e.g., Button myButton = new Button();), you'll need to call setLayoutParamson the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

如果通过构造函数(例如Button myButton = new Button();)创建视图,则需要调用setLayoutParams新构造的视图,传入父视图的 LayoutParams 内部类的实例,然后再将新构造的子视图添加到父视图。

For example, you might have the following code in your onCreate()function assuming your LinearLayout has id R.id.main:

例如,onCreate()假设您的 LinearLayout 具有 id ,您的函数中可能包含以下代码R.id.main

LinearLayout myLayout = findViewById(R.id.main);

Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.MATCH_PARENT,
                                     LinearLayout.LayoutParams.MATCH_PARENT));

myLayout.addView(myButton);

Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.

确保设置 LayoutParams 很重要。每个视图至少需要一个 layout_width 和一个 layout_height 参数。获得正确的内部类也很重要。我一直在努力将视图添加到 TableRow 以正确显示,直到我发现我没有将 TableRow.LayoutParams 的实例传递给子视图的 setLayoutParams。

回答by ndori

for anyone yet interested:

对于任何感兴趣的人:

the best way I found is to use the inflate static method of View.

我发现的最好方法是使用 View 的 inflate 静态方法。

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

where yourViewXML is something like R.layout.myView

其中 yourViewXML 类似于 R.layout.myView

please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)

请注意,您需要一个 ViewGroup 才能添加视图(这是您能想到的任何布局)

so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:

举个例子,假设你有一个片段,它的视图已经被膨胀,你知道根视图是一个布局,你想向它添加一个视图:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

回答by AndroidOptimist

This is late but this may help someone :) :) For adding the view programmatically try like

这很晚了,但这可能对某人有所帮助:) :) 对于以编程方式添加视图,请尝试像

LinearLayout rlmain = new LinearLayout(this);      
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);          
LinearLayout   ll1 = new LinearLayout (this);

ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);              
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);              
setContentView(rlmain, llp);

This will create your entire view programmatcally. You can add any number of view as same. Hope this may help. :)

这将以编程方式创建您的整个视图。您可以添加任意数量的相同视图。希望这可能会有所帮助。:)

回答by Klarth

LinearLayoutis a subclass of ViewGroup, which has a method called addView. The addViewmethod should be what you are after.

LinearLayoutViewGroup的子类,它有一个名为addView的方法。该addView方法应该是你所追求的。

回答by yoAlex5

One more way to add view from Activity

从 Activity 添加视图的另一种方法

ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);

回答by kush

The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.

以编程方式设置约束的想法可能令人厌烦。下面的这个解决方案适用于任何布局,无论是约束、线性等。最好的方法是在您期望以编程方式创建的视图的位置设置一个占位符,即具有适当约束的 FrameLayout(或适当放置在其他布局中,例如线性)具有。

All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild()method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout[link].

您需要做的就是通过使用addChild()方法以编程方式扩展视图并将其作为 FrameLayout 的子项。然后在运行时您的视图将被膨胀并放置在正确的位置。根据 Android 建议,您应该只向 FrameLayout [link]添加一个 childView 。

Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:

假设您希望在特定位置以编程方式创建 TextView,则您的代码如下所示:

Step 1:

第1步:

In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".

在包含要膨胀的视图的布局中,将 FrameLayout 放置在正确的位置并为其指定一个 id,例如“容器”。

Step 2Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :

步骤 2使用根元素创建布局作为您要在运行时膨胀的视图,将布局文件称为“textview.xml”:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

</TextView>

BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.

顺便说一句,始终将 frameLayout 的 layout-params 设置为 wrap_content,否则框架布局将变得与父级(即活动,即电话屏幕)一样大。

android:layout_width="wrap_content"
android:layout_height="wrap_content"

If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.

如果没有设置,因为框架的子视图默认情况下会到达框架布局的左上角,因此您的视图只会飞到屏幕的左上角。

Step 3

第 3 步

In your oncreate method, do this :

在您的 oncreate 方法中,执行以下操作:

FrameLayout frameLayout = findViewById(R.id.container);
                TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
                frameLayout.addView(textView);

(Note that setting last parameter of findViewByIdto nulland adding view by calling addView()on container view (frameLayout) is same as simply attaching the inflated view by passing truein 3rd parameter of findViewById(). For more, see this.)

(请注意,设置findViewByIdto 的最后一个参数null并通过调用addView()容器视图(frameLayout)添加视图与通过传入true的第三个参数来附加膨胀视图相同findViewById()。有关更多信息,请参阅。)

回答by Oz Shabat

You guys should also make sure that when you override onLayoutyou HAVE to call super.onLayoutwith all of the properties, or the view will not be inflated!

你们还应该确保在覆盖时必须使用所有属性onLayout调用super.onLayout,否则视图不会膨胀!