Android layout View.measure () dynamically take height and set layout-(example: Dynamic calculation of comment height and display)

Source: Internet
Author: User

The requirement is this :

In the application details, there are comments on the section, the page comments up to 5, and each of the maximum number of words is 140 characters, each comment may vary depending on the number of words, occupy a different height, such as some 1 lines, some 2, 3 lines, and comments can be page.

The picture works as follows:




How to solve such a problem?

The first thing to know is that the comment control does not have to be fixed, but it needs to be dynamically calculated and dynamically added to the display panel.

Let's take a look at the example below.

1. Defining layouts

When defining the layout, you can use Absolutelayout, because the height is dynamic, so the specific coordinates can be obtained. Refer to the following:

<absolutelayout        android:layout_width= "1386px"        android:layout_height= "Wrap_content"        android: layout_margintop= "60px"        android:id= "@+id/comment_content" >         </AbsoluteLayout>
The layout file width is set unchanged and the height is populated based on the content. Just put this layout side where you need to display the comment content.

2. Display Data


To display the data, you need to calculate the height based on the data, first set the data to the control, and then View. Measure (int widthmeasurespec, int heightmeasurespec) Take height, and set the coordinates for the view. Reference code:

<span style= "FONT-SIZE:14PX;" >/** * Initialize, dynamically calculate height */public void Initcommentview () {record_temp = new Commentrecord (); Mpositionrecord = new Arraylist&lt ;integer> (); Mheightrecord = new arraylist<integer> (); int currentheight = 0;int Maxnum = Cachedcomments.size (); int sum = 0;for (int i = Comment_begin_index; i < maxnum; i++) {if (null! = Mcommentcache &&!mcommentcache.emp Ty ()) {comment_temp = Mcommentcache.pop ();} else {comment_temp = new Commentsimpleview (mcontext);} Mcommentui.add (comment_temp); Comment_temp.setdata (Cachedcomments.get (i)); Comment_temp.measure (width, height); if (Max_comment_height > Currentheight) {Comment_content.addview (comment_temp,new absolutelayout.layoutparams (1386, Comment_temp.getmeasuredheight (), 0, first_comment_interval+ currentheight)); Mpositionrecord.add (First_comment_interval + currentHeight); Mheightrecord.add (Comment_temp.getmeasuredheight ()); currentheight = currentheight+ comment_temp.getmeasuredheight (); comment_end_index++;sum++;if (Sum < 5) {Comment_temp.show_divider ();} else if (sum = = 5) {Comment_temp.hide_divider ();}} if (Max_comment_height < currentheight) {compareheight = 1;isend = false; Relativelayout.layoutparams RL = (layoutparams) comment_content.getlayoutparams () rl.setmargins (0, 0, 0); rl.width = 1386;rl.height = Max_comment_height+20;comment_content.setlayoutparams (RL); if (max_comment_height = = currentheight) {compareheight = 0;if (Maxnum = = comment_end_index) {isend = True;comment_pagedow N.setfocusstatus (false);} else {isend = false;}}} Record_temp.setheightrecord (Mheightrecord); Record_temp.setpositionrecord (Mpositionrecord); record_temp.setBegin _index (Comment_begin_index); Record_temp.setend_index (Comment_end_index); if (Max_comment_height > CurrentHeight {isend = True;comment_pagedown.setfocusstatus (false);}} </span>
Where the global width and height are defined as follows:

int width = Measurespec.makemeasurespec (1386, measurespec.exactly);
int height = measurespec.makemeasurespec (0, measurespec.unspecified);

3. Dynamic calculation Implementation of page turn

/** * Click on the next page, determine if there is space remaining, if there is a previous page of data supplement, false: No remaining * @return */private boolean hasextraspace () {if (null! = Cachedcomments &am p;& cachedcomments.size ()-comment_end_index >=5) {//The remaining comments are greater than 5 return false;} int beginindex = 0;if (1 = = compareheight) {beginindex = Comment_end_index;} else if (0 = = compareheight) {beginindex = comment_end_index+1;} int maxSize = Cachedcomments.size (), int heightsum = 0;for (int i = beginindex;i<maxsize;i++) {comment_temp = new CommentS Impleview (Mcontext); Comment_temp.setdata (Cachedcomments.get (i)); Comment_temp.measure (width, height); Heightsum + = Comment_temp.getmeasuredheight (); if (Max_comment_height <= heightsum) {return false;}} Lastpageheight = Heightsum;return true;} /** * Last page not one screen, for the penultimate page, from the last reverse order, */public void Showlastpage () {int lastcommentnum = Cachedcomments.size ()-Comment_end_ Index;int Copy_last_index = comment_end_index;while (<= max_comment_height-lastpageheight) {lastCommentNum + +; Comment_temp = new Commentsimpleview (mcontext); comment_temp.setData (Cachedcomments.get (--copy_last_index)); comment_temp.measure (width, height); lastpageheight+=comment_ Temp.getmeasuredheight ();} if (Max_comment_height < lastpageheight) {lastcommentnum-; Lastpageheight-= Comment_temp.getmeasuredheight (); Copy_last_index + +;} int sum = cachedcomments.size (), int current_h = First_comment_interval + max_comment_height-lastpageheight;for (int i= Co py_last_index;i<sum;i++) {if (null! = Mcommentcache &&!mcommentcache.empty ()) {comment_temp = Mcommentcache.pop ();} Else{comment_temp = new Commentsimpleview (mcontext);} Mcommentui.add (comment_temp); Comment_temp.setdata (Cachedcomments.get (i)); Comment_temp.measure (width, height); Comment_content.addview (Comment_temp, New Absolutelayout.layoutparams (1386, Comment_temp.getmeasuredheight (), 0, Current_h)); current_h = Current_h + comment_temp.getmeasuredheight (); if (i = = sum-1) {Comment_temp.hide_divider ();} Else{comment_temp.show_divider ();}} Isend = True;comment_pagedown.setfocusstatus (false);} /** * Click on the previous page, out of the stack, restores the data and displays */public void Showpageup () {if (Mcommentrecord.empty ()) {Toast.maketext (Mcontext, "Already the first page", Toast.length_short ). Show (); return;} Record_temp = Mcommentrecord.pop (); int begin = Record_temp.getbegin_index (); int end = Record_temp.getend_index (); list<integer> position = Record_temp.getpositionrecord (); list<integer> height = Record_temp.getheightrecord (); if (null = = Position | | null = = height) {return;} int m = 0;for (int i= begin;i<=end;i++) {if (null! = Mcommentcache &&!mcommentcache.empty ()) {comment_temp = mcom Mentcache.pop ();} Else{comment_temp = new Commentsimpleview (mcontext);} Mcommentui.add (comment_temp); Comment_temp.setdata (Cachedcomments.get (i)); Comment_content.addview (Comment_temp, New Absolutelayout.layoutparams (1386,height.get (m), 0, Position.get (m)); M++;if (5 = = m) {Comment_temp.hide_divider () ;} Else{comment_temp.show_divider ();}} Isend = False;comment_begin_index = Begin;comment_end_index = end;}

4. Click on the previous page, next page event processing

public class Comment_pageup_click implements Okbuttonviewclick {@Overridepublic void Onokbuttonviewclick () {if (1 = = CurrentPage) {//toast.maketext (Mcontext, "Already the first page", Toast.length_short). Show (); Comment_pageup.setfocusstatus (false) ; return;} Else{currentpage = Currentpage-1;comment_content.removeallviews (); while (!mcommentui.isempty ()) { Mcommentcache.push (mcommentui.remove (0));} Showpageup (); Comment_pagedown.setfocusstatus (True);}}} Class Comment_pagedown_click implements Okbuttonviewclick {@Overridepublic void Onokbuttonviewclick () {if (isend) {// Toast.maketext (Mcontext, "Already the last page", Toast.length_short). Show (); Comment_pagedown.setfocusstatus (false); return;} else if (!isend) {//less than the last page if (!hasextraspace ()) {///the next page has no space left, that is, the page is not the penultimate page Mcommentrecord.push (record_temp); currentpage = CurrentPage + 1;if (1 = = compareheight) {Comment_begin_index = Comment_end_index;comment_end_index--;} Else{comment_begin_index = comment_end_index+1;} if (currentpage%4 ==0) {//Pre-load Data Parserhelper.getparserhelper (). Requestcomment ("1", "9", "callback"); Comment_content.removeallviews (); while (!mcommentui.isempty ()) {Mcommentcache.push (mcommentui.remove (0));} Initcommentview ();} else {//The next page has the remaining space, that is, the page is the penultimate page Mcommentrecord.push (record_temp); currentpage = CurrentPage + 1;comment_ Content.removeallviews (); while (!mcommentui.isempty ()) {Mcommentcache.push (mcommentui.remove (0));} Showlastpage ();} Comment_pageup.setfocusstatus (True);}}}

5. Save State on next page click to use as recovery. (save with stack, stack out stack)
Package Com.helios.module.commentdata;import Java.util.list;public class Commentrecord {int Begin_index;int end_index ; List <Integer> Positionrecord; List <Integer> heightrecord;public Commentrecord () {super ();} public int Getbegin_index () {return begin_index;} public void Setbegin_index (int begin_index) {this.begin_index = Begin_index;} public int Getend_index () {return end_index;} public void Setend_index (int end_index) {this.end_index = End_index;} Public list<integer> Getpositionrecord () {return positionrecord;} public void Setpositionrecord (list<integer> positionrecord) {This.positionrecord = Positionrecord;} Public list<integer> Getheightrecord () {return heightrecord;} public void Setheightrecord (list<integer> heightrecord) {This.heightrecord = Heightrecord;}   }


6. Concluding wordsDynamic Computing, the dynamic layout is still very common. The key is that the use of the measure () method, set the data can be measure (), the amount of height, and then set to the display panel, that is called:Viewgroup.addview (View Child,Layoutparams params first write dynamic layout, write bad, I hope you do not spray, there are questions welcome message discussion, we learn from each other, slowly progress.

Android layout View.measure () dynamically take height and set layout-(example: Dynamic calculation of comment height and display)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.