Android dynamically adds views or items and obtains instances of data

Recently, a function was used in a project, which requires dynamic items, and there are multiple cases. However, after careful analysis, they are similar and easy to do. Here, I only extracted and made a demo, and only made a dynamically added item. At the same time, I can obtain all the data on the added and edited items, as shown in the figure above:

Let's analyze the demo first:

Two textviews and EditText, a button and a star rating ratingbar control. The layout is finished

activity_ Multiple dynamic layouts may be added, so we use Scrollview outside. Because we add them vertically, we use LinearLayout as a container

Take another look at the item to be added_ hotel_ Layout in evaluate:

The layout is good, because the code in the activity is not written very much. You can directly write the code, and then analyze it at the end:

Finally, let's interpret the code:

Oncreate initializes the control and sets events. At the same time, we add an item by default. Because there is no child view in the addhotelnameview container during initialization, we pass null to the added method by default,

In addviewitem method, the button method is initialized and set. Therefore, in onclick method, the V of the event is passed in to mark, that is, set tag. There are two situations when adding:

1. If there is only one, we can only display add

2. When there are multiple items, if you click Add with the tag set as add, you can add

If you click delete, the delete click event has been set in the sorthotelviewitem method and is deleted directly from memory,

Finally, get the data. We can traverse addhotelnameview. Getchildcount () through the LinearLayout container to get all the added items, and then find the ID of the control to get all the added item data.

Here's another note: it can be optimized in the addviewitem method. It has been packaged when uploading resources. Now four lines are commented out in a single line. There is no need to sort when adding the first item. There is dead code in else. Friends who download resources can delete these lines.

The above example of Android dynamically adding views or items and obtaining data is all the content shared by Xiaobian. I hope it can give you a reference and support more 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
分享
二维码
< <上一篇
下一篇>>