Android uses addview to dynamically add components

In project development, we often need to add components dynamically. There are two parts that can be added: layout and components

Among them, the added layouts mainly include relativelayout (relative layout) and LinearLayout (linear layout)

The added components mainly include text display box, edit box, button and other components.

Let's implement it below:

First, we create a new project and delete mainactivity Class, leaving only the protected void oncreate (bundle savedinstancestate) function to add a new component to the layout file:

1. Introduction to addview method

In Android, addview (ViewGroup view, index) adds a view at the specified index. You can use the addview function of the typesetting view to add the dynamically generated view object to the typesetting view.

2. Example:

(1) First, we add a component to the layout file, such as a text and two buttons. At this time, we need to add a layout item < LinearLayout > in the layout file and define its ID as linearlay_ 1. It is used to identify when adding components. The layout file code is as follows:

Then we add components in the activity class. The code is as follows:

The effect is shown in the following figure:

Figure 1 dynamically adding components - LinearLayout

(2) Add layout dynamically:

*The following example will introduce how to dynamically add a layout. The basic content is consistent with the above code, mainly focusing on how to control the location of the added layout

*The layoutparam class is used to control the position of the layout.

*Note: when controlling the position and style, the layout and control use the same method.

*/This operation is only performed in mainactivity and does not involve layout file (. XML). Its code is as follows:

The effect is as follows:

Figure 2 dynamic adding layout - relativelayout

After learning the above introduction, you can easily layout the interface, whether buttons or other components. For the layout, you can also easily use the layout. The above is how to dynamically add components in Android.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>