GitHub Project parsing (eight)-->activity three ways to get the component's width high during startup

Source: Internet
Author: User
Tags call back

Reprint please indicate the source: a column of Maple Leaf

In the last GitHub small project we introduced a small frame that prevents the button from repeating a click, and the core logic of its implementation is to rewrite the Onclicklistener onclick method and add the logic to prevent repeated clicks, that is, to add a threshold for the second click and the time interval of the first click. If the second click of the time interval and the first click of the time interval is less than the threshold, then this click is not valid, again on the basis of We also encapsulated the Click Component Verification Network Listener, click on the component to verify whether login listener, etc., specific reference: GitHub project Resolution (vii) –> Prevent buttons from repeating clicks

In this article I'll show you three ways to get the component's width high when activity starts in Android. We know that sometimes we need to get a component's width or height for dynamic changes to the UI layout file when the activity starts, but it is problematic to get directly through the GetWidth and GetHeight methods. Why do you say that? Here we can check the next Test example to verify:


Problem:

    • Gets the width and height of the component through the GETWIDHT and GetHeight methods during the activity's startup process
/** * 在onCreate方法中调用,用于获取TextView的宽度和高度 */privatevoidgetTextHeightAndWidth() {        // 我们定义的用于获取宽度和高度的组件        titleText = (TextView) findViewById(R.id.text_title);        int height = titleText.getHeight();        int width = titleText.getWidth();        "height:""  ""width:" + width);    }

This code seems to be normal, but we will write the code in the OnCreate method, after executing this code, the result of printing:

06-2620:12:15.35619453-19453/uuch.com.android_viewheight I/MainActivity: height:0  width:0

Hey? Why is the height and width of the print 0? We're doing it again? The result is still the same, two variables are 0, is this code can no longer be called in the OnCreate method, then we try to call in the Onresume method?

Can only say the egg, print the result is still:

06-2620:52:13.98619453-19453/uuch.com.android_viewheight I/MainActivity: height:0  width:0

Well, the problem has come out, it seems that we can no longer oncreate method or Onresume method calls the method to get the width of the component, but this is why? Usually we are in this way to get the width of the component, and it is not a problem, such as we write the method of the invocation logic in the button click event? Let's try it again.

/** * 这里的button1是我们定义的Button组件,并且我们重写了Button的点击事件,在其中调用了获取组件宽高的方法 */button1 = (Button) findViewById(R.id.button1);button1.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View v) {                getTextHeightAndWidth();            }        });

After the code has been knocked out, we execute the code, and the interface looks like this:

What about the results of our printing?

06-2620:57:08.18822648-22648/uuch.com.android_viewheight I/MainActivity: height:57  width:225

Well? At this point we find that it prints out the width and height of the components, so why do we print the OnCreate and Onresume methods of the activity, the output of the component width is 0?


Reason:

Actually, I've seen what I've written before.
Android Source code Analysis (14) –>activity START process
Android Source code parsing (17) –>activity Layout loading process
Android source code parsing (18) –>activity layout drawing Process
Students should be on the activity of the START process and its layout loading drawing process is not strange, the activity of the start process and activity layout file loading drawing process, in fact, there is no related relationship, in fact, two asynchronous loading process, This way, when we call Textview.getheight or the Textview.getwidth method in the activity's OnCreate and Onresume methods, its components do not finish the drawing process, so the width of the component obtained at this time is the default of 0, that is, unable to get the group The width and height of the pieces.

However, when we will get the component wide-height method to unload the Click event of the button, because the button has been displayed, so that the layout file has been loaded to complete the drawing, then click on the component actor to obtain a wide-height method, you can normally get the width and height of the component.

This is why we call the Get component width height in the OnCreate and Onresume methods to 0, while the button's Click event gets the normal reason.


Other solutions:

So what if we want to get the width of the component in the OnCreate method or the Onreusme method of the activity? The following three ways are available:

    • Onwindowfocuschanged method for overriding activity
/** * Rewrite Acitivty's onwindowfocuschanged method */ @Override     Public void onwindowfocuschanged(BooleanHasfocus) {Super. onwindowfocuschanged (Hasfocus);/** * When Hasfocus is true, the activity's window object has already gained focus, and the activity interface has been loaded to finish the drawing */        if(Hasfocus) {intWIDHT = Titletext.getwidth ();intHeight = titletext.getheight (); LOG.I (TAG,"onwindowfocuschanged width:"+ WIDHT +"   "+"Height:"+ height; }    }


Description

This overrides the Onwindowfocuschanged method, and when we get the focus we can get the width and height of the component through the GetWidth and GetHeight methods. But at this point the logic of this method may be executed several times, that is, as long as our Activity's Window object takes the focus to execute the statement, so we need to do some logic to make it when we need to print to get the component of the height of the execution.

    • Adding Ongloballayoutlistener event listeners to a component
/** * Add Ongloballayoutlistener Event listener for the activity's layout file, When we call back to the Ongloballayout method we can get the width and height of the component through the Getmeasureheight and Getmeasuredwidth methods */Private void Initonlayoutlistener() {FinalViewtreeobserver Viewtreeobserver = This. GetWindow (). Getdecorview (). Getviewtreeobserver (); Viewtreeobserver.addongloballayoutlistener (NewViewtreeobserver.ongloballayoutlistener () {@Override             Public void Ongloballayout() {log.i (TAG,"Start executing ongloballayout () ...");intHeight = titletext.getmeasuredheight ();intwidth = Titletext.getmeasuredwidth (); LOG.I (TAG,"Height:"+ Height +"width:"+ width);    }        }); }

Description

It should be explained that the Ongloballayout method here will be executed after the activity component executes the OnLayout method, here the OnLayout method is mainly used to calculate the width and height of the component operation, specific reference: Android source code Analysis (18) –> Activity layout drawing process, so that when we calculate the width of the component and then perform the get component's wide-height operation, we can naturally get the width and height of the component.

    • Adding Onpredrawlistener event listeners to a component
/** * Initialize Viewtreeobserver event listener, override Onpredrawlistener Get component Height * /    Private void Initonpredrawlistener() {FinalViewtreeobserver Viewtreeobserver = This. GetWindow (). Getdecorview (). Getviewtreeobserver (); Viewtreeobserver.addonpredrawlistener (NewViewtreeobserver.onpredrawlistener () {@Override             Public Boolean Onpredraw() {log.i (TAG,"Start executing onpredraw () ...");intHeight = titletext.getmeasuredheight ();intwidth = Titletext.getmeasuredwidth (); LOG.I (TAG,"Height:"+ Height +"width:"+ width);return true;    }        }); }

Description

It is important to note that the Onpredraw method here will be executed before the activity component executes the OnDraw method, and the students who are familiar with our activity component loading drawing process should know that the OnDraw method here is mainly used to perform the actual drawing component operation. At this time we have calculated the position of the component, wide and high operation, so that after the acquisition of the component's wide-height operation, the natural ability to obtain the width and height of the component.


Other Notes:

It should be explained that if the Acitivty layout loading drawing process to understand the students should know that the interface display process through: Measuring position, measuring size, drawing, three operating procedures. And we get the width of the component is to get the size of the component, so we get the code must be done after the component execution measurement size, regardless of the onwindowfocuschanged method we added, Onpredrawlistener monitoring, Already ongloballayoutlistener monitoring is actually performed after the component has finished measuring size, so we can get the width and height of the component correctly at this time.


Summarize:

    • This kind of library mainly introduces three kinds of ways that we get the component's width and height in the activity startup process;

    • The way to get the component's width by overriding the Onwidnowfocuschanged method can be recalled several times, which requires our attention;

    • Project Save Address: Android-viewheight, Welcome to star and follow


In addition to the GitHub project, open source project analysis of interested students can refer to my:
GitHub Project Resolution (i) –> upload Android project to GitHub
GitHub Project Resolution (ii) –> to publish Android projects to the Jcenter code base
GitHub Project Resolution (III) –>android memory leak monitoring leakcanary
GitHub Project Resolution (iv) –> dynamically change the font size of TextView
GitHub Project Parsing (v) –>android log Framework
GitHub Project Resolution (VI) –> custom implementation Butterknife Framework
GitHub Project Parsing (vii) –> prevent button repeat click

GitHub Project parsing (eight)-->activity three ways to get the component's width high during startup

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.