Recent project requirements, need to get the number of TextView, by comparing the number of rows with the TextView maxlines to determine whether to show whether the expansion button below the TextView is displayed, less nonsense to say directly on the code, Mtextview.getlinecount () , it seems nice, Android has provided this method, but always returns 0, which is why? The official notes are as follows:
/**
* Return the number of lines of text, or 0 if the internal Layout has not
* Been built.
*/
This means that only the internal layout is created and the correct number of rows is returned, so how do you ensure that layout is created?
Finally, that's how I solved it.
Mtextview.getviewtreeobserver (). Addongloballayoutlistener (New Ongloballayoutlistener () {
@Override
public void Ongloballayout () {
TODO auto-generated Method Stub
LOG.E (TAG, "Number of Rows" +mtextview.getlinecount ());
Mtextview.getviewtreeobserver (). Removeglobalonlayoutlistener (this);
if (Mtextview.getlinecount () >0) {
Mtextview.getviewtreeobserver (). Removeongloballayoutlistener (this);
}
}
});
When TextView is drawing, it will call back this method, notice that when we get the desired value, we take care to remove the globalonlayoutlistener to avoid unnecessary execution, and my project needs are to be followed by a change in the height of the TextView to achieve a smooth expansion of the animation. Attach key code
/**
* Folding Effect
*/
Temphight = Mtextview.getlineheight () * Mtextview.getlinecount ()-starthight; Calculate to expand Height
Temphight = Mtextview.getlineheight () * maxline-starthight;//is negative, the height of contraction
Animation Animation = new Animation () {
Interpolatedtime the relative time corresponding to the current animation frame, the value is always between 0-1
protected void Applytransformation (float interpolatedtime, transformation t) {
Mtextview.setheight ((int) (Starthight + temphight * interpolatedtime))///original length + height difference * (gradients from 0 to 1) are animated
}
};
Animation.setduration (1000);
Mtextview.startanimation (animation);
Android gets TextView number of rows