The Android UI implements a multiline text folding expansion effect _android

Source: Internet
Author: User
Tags gettext

This paper introduces the horizontal touch sliding effect of single line text, and realizes the horizontal sliding effect of textview text by EditText.

This article continues to introduce multiple lines of text folding expansion, custom layout view implementation for multiline text folding and expansion

1. Overview

Often in the app can see the reference article or a large section of the content of the post, their display style is also somewhat interesting, the default is folded, when you click on the article it will automatically expand. Click again and he will shrink back.
Some of the results found on the internet, the feeling is not very satisfied. Finally, I tried to write a demo with a custom layout layout. It's simple, but it can be used. Friends with this need can be slightly modified. If you have a better idea, you might as well share it.

Effect Chart:

2 . Concrete implementation

But from the realization of the effect, only a simple definition of the necessary view can, after the change in order to facilitate the expansion of the use and misappropriation, and the entire layout of the package, easy to use directly.

2.1 Implementation through multiple layout combinations

The first idea, of course, is to use multiple view combinations. For so long define a linearlayout layout nested textview and ImageView respectively.

Approximate steps:

-Define layouts, vertical linear linearlayout layouts, TextView, and ImageView. Define the basic components in the layout.
-Sets the height of the TextView to the specified number of lines * Row height. The reason for not using maxline is that Maxline controls the number of lines that display text, and it is inconvenient to use animations to expand the entire contents. So the height of the TextView here is also due to the wrap_content.
-Add a Click event to the entire layout and bind the animation. Click, if TextView is not expanded to its actual height, imageview rotation, otherwise back to the specified number of rows * Row height, imageview rotation retract.

To start writing code:

1. Define the layout in XML:

 <linearlayout
 android:id= "@+id/description_layout"
 android:layout_width= "Match_parent"
 android: layout_height= "Wrap_content"
 android:orientation= "vertical"
 android:paddingleft= "12dip"
 android: paddingright= "12dip"
 android:paddingtop= "5dip" >

 <textview
 android:id= "@+id/description_view"
 android:layout_width= "match_parent"
 android:layout_height= "wrap_content"
 android:textcolor= "@ Android:color/black "
 android:textsize=" 18dip ">
 </TextView>

 <imageview
 android: Id= "@+id/expand_view"
 android:layout_width= "wrap_content"
 android:layout_height= "Wrap_content
 " Android:layout_gravity= "right"
 android:paddingbottom= "5dip"
 android:paddingleft= "5dip"
 android: paddingright= "5dip"
 android:paddingtop= "5dip"
 android:src= "@drawable/text_ic_expand"
 android: visibility= "Gone"/>
 </LinearLayout>

2. First define and initialize these view in the activity:

public class Mainactivity extends activity {
 TextView descriptionview;
 View Layoutview, Expandview; LinearLayout layout and ImageView
 int maxdescripline = 3;//textview default maximum number of display rows

 //Initialize
 {oncreate in Layoutview
 = Findviewbyid (r.id.description_layout);
 Descriptionview = (TextView) Findviewbyid (R.id.description_view);
 Expandview = Findviewbyid (R.id.expand_view);
 }
}

3. Then set the TextView display text, and then set its height according to the default number of display lines, and decide whether you need to click More buttons to see if they are fully displayed (the current number of rows is greater than or equal to the actual number of rows).

 Sets the text
 descriptionview.settext (GetText (r.string.content));

 Descriptionview Sets the default display height
 descriptionview.setheight (descriptionview.getlineheight () * maxdescripline);
 Depending on the height to determine if you need to click Expand
 descriptionview.post (New Runnable () {

 @Override public
 void Run () {
 Expandview.setvisibility (Descriptionview.getlinecount () > Maxdescripline? View.VISIBLE:View.GONE);
 }
 ); 

Because the TextView is set to Wrap_content, the actual height and number of rows are displayed, where the height is set according to Maxdescripline.
Look at the last line of code maybe someone will ask? ImageView (click to expand More) should the judgment logic be displayed in the Post method? This is because the TextView of the settings defined in the OnCreate method is not immediately rendered and displayed, so TextView getlinecount () gets a generally zero value, so using post will display control of the ImageView after its drawing completes.
PS: It feels like I can't describe a friend who can look at the StackOverflow on the tutorial on how to use Getlinecount () in TextView Android.

4. Set Click events for Layoutview.

Define a rotateanimation rotation animation for the ImageView, control the TextView height according to the rotational percent progress in the rotation process, and then achieve the desired effect.

 Layoutview.setonclicklistener (New View.onclicklistener () {Boolean isexpand;//whether the state is expanded @Override public void OnClick (View v)
 {Isexpand =!isexpand; Descriptionview.clearanimation ()//Clear animation effect final int deltavalue;//default height, which is the height final int startvalue determined by maxline 
  Descriptionview.getheight ()//start height int durationmillis = 350;//animation duration if (isexpand) {/** * collapse animation * Retract starting height from actual height * *
  Deltavalue = Descriptionview.getlineheight () * Descriptionview.getlinecount ()-startvalue; rotateanimation animation = new Rotateanimation (0, 180, animation.relative_to_self, 0.5f, Animation.relative_to_self,
  0.5f);
  Animation.setduration (Durationmillis);
  Animation.setfillafter (TRUE);
 Expandview.startanimation (animation); else {/** * Expand animation * from start height to actual height * * deltavalue = descriptionview.getlineheight () * Maxdescripline-startvalue
  ; rotateanimation animation = new Rotateanimation (180, 0, Animation.relative_to_self, 0.5f, Animation.relative_to_self,
  0.5f); Animation.setduratioN (durationmillis);
  Animation.setfillafter (TRUE);
 Expandview.startanimation (animation); } Animation Animation = new Animation () {protected void applytransformation (float interpolatedtime, transformation t) {//The TextView height is displayed according to the percentage of the ImageView rotation animation, and the animation effect Descriptionview.setheight ((int) (Startvalue + Deltavalue *
  Interpolatedtime));
 }
 };
 Animation.setduration (Durationmillis);
 Descriptionview.startanimation (animation);

 }
 });

At this point, through the layout has achieved the effect we want. Specific code see the first part of the code example.
Of course, we can use this, but it's a bit of a hassle to rewrite it every time. Therefore, it is necessary to write him a separate control, to facilitate the future of our open bag ready-to-eat. Don't say much nonsense, serve the dishes.

2.2 Through Custom view combination encapsulation

The layout structure of this view is not intended to define layout using XML, directly defining a Moretextview class that inherits LinearLayout. This class adds TextView and ImageView.

1. Use styleable to customize the View property

For the convenience of using Moretextview this custom view in the XML layout, similar to the

Android:text = "XXX"
Android:textsize = "XXX"

With such fast binding text content and setting the font size properties, we can customize the attributes we want by declare-styleable the XML in the values file and get and use them in view. Detailed use of declare-styleable content will be supplemented, here briefly.
For example, Moretextview should have some basic attributes, such as text font size (textsize), Color (textcolor) and text content, and the default number of rows (maxline). We want to imagine TextView. Set bindings directly in XML, you can do this.
First create a new attrs.xml in the values directory (the name is random), and define these attributes Moretextview.

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
 <declare-styleable name= "Moretextstyle" >
 <attr name= "textsize" format= "Dimension"/> <attr name= "
 textcolor" format= "Color"/>
 <attr name= "Maxline" format= "integer"/> <attr name=
 "text" format= "string"/>
 </ Declare-styleable>
</resources>

2. Customize Moretextview and get the values of these properties

These attributes are defined above, which is tantamount to allowing us to use in XML

More:text = "XXX"
More:textsize = "XXX"
More:textcolor = "XXX"
More:maxline = "XXX"
(Note: More This keyword can be arbitrary)

This sets the property value directly. So exactly how to get the value, we'll talk later.

(1) Define the properties of the Moretextview:

public class Moretextview extends linearlayout{
 protected TextView contentview;//Text body
 protected ImageView Expandview; Expands

 the button//corresponds to the attribute in the styleable
 protected int textcolor; 
 protected float textsize;
 protected int maxline;
 protected String text;

 Default property value public
 int defaulttextcolor = Color.Black;
 public int defaulttextsize =;
 public int defaultline = 3;

 //.... Implementation section slightly
}

(2) The construction method of Moretextview:

 Public Moretextview (context, AttributeSet attrs) {
 Super (context, attrs);
 Initalize (); 
 Initwithattrs (context, attrs); 
 Bindlistener ();
 }

These three methods are described briefly below:

initalize () Initialize and add view. Initialize TextView and ImageView, and add them to the Moretextview.
initwithattrs (context, Attrs) value and set. Use Attrs to get the attribute values from the XML layout that we have configured for the Text/textsize/textcolor/maxline, and set the view up.
Bindlistener () binds the event and sets the animation. Set the Click event for the current Moretextview to achieve click Folding and expansion.

Specific implementations of each method:

Initialize and add view
protected void Initalize () {
 setorientation (VERTICAL);//Set Vertical layout
 setgravity (gravity.right) ; Right align
 //Initialize TextView and add
 Contentview = new TextView (GetContext ());
 AddView (Contentview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
 Initialize ImageView and add
 Expandview = new ImageView (GetContext ());
 int padding = dip2px (GetContext (), 5);
 expandview.setpadding (padding, padding, padding, padding);
 Expandview.setimageresource (R.drawable.text_ic_expand);
 Linearlayout.layoutparams LLP = new Linearlayout.layoutparams (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
 AddView (Expandview, LLP);

It is necessary to take a value and set this part. We use Typedarray to remove the attribute values from the defined styleable and assign the property variables to our well-defined classes. Remember to call recycle () to reclaim the release after you have finished taking it.

 protected void Initwithattrs (context context, AttributeSet attrs) {TypedArray a = Context.obtainstyledattributes (attrs 
 , R.styleable.moretextstyle); int textcolor = A.getcolor (R.styleable.moretextstyle_textcolor, Defaulttextcolor); Take the color value, default Defaulttextcolor textsize = A.getdimensionpixelsize (r.styleable.moretextstyle_textsize, DefaultTextSize) //color font size, default defaulttextsize maxline = A.getint (R.styleable.moretextstyle_maxline, defaultline); Default Defaultline Text = a.getstring (r.styleable.moretextstyle_text);//Get text content//bind to TextView Bindtextview (TextColor,

 Textsize,maxline,text); A.recycle ();//Recycle release}//bind to TextView protected void Bindtextview (int color,float size,final int line,string text) {con
 Tentview.settextcolor (color);
 Contentview.settextsize (typedvalue.complex_unit_px,size);
 Contentview.settext (text);
 Contentview.setheight (Contentview.getlineheight () * line); Post (new Runnable () {//previously spoken, no longer repeat @Override public void run () {expandview.setvisibility CONTENTVIEw.getlinecount () > line?

 View.VISIBLE:View.GONE);
 }
 });

 }

The

Finally sets the Click event.

 Click Expand and collapse, no longer repeat protected void Bindlistener () {Setonclicklistener (new View.onclicklistener () {Boolean isexpand;
 @Override public void OnClick (View v) {isexpand =!isexpand;
 Contentview.clearanimation ();
 final int deltavalue;
 Final int startvalue = Contentview.getheight ();
 int durationmillis = 350;
  if (isexpand) {deltavalue = Contentview.getlineheight () * Contentview.getlinecount ()-startvalue; rotateanimation animation = new Rotateanimation (0, 180, animation.relative_to_self, 0.5f, Animation.relative_to_self,
  0.5f);
  Animation.setduration (Durationmillis);
  Animation.setfillafter (TRUE);
 Expandview.startanimation (animation);
  else {deltavalue = Contentview.getlineheight () * maxline-startvalue; rotateanimation animation = new Rotateanimation (180, 0, Animation.relative_to_self, 0.5f, Animation.relative_to_self,
  0.5f);
  Animation.setduration (Durationmillis);
  Animation.setfillafter (TRUE);
 Expandview.startanimation (animation); } Animation Animation = nEW Animation () {protected void applytransformation (float interpolatedtime, transformation t) {Contentview.setheight ( (int)
  (Startvalue + deltavalue * interpolatedtime));
 }

 };
 Animation.setduration (Durationmillis);
 Contentview.startanimation (animation);
 }
 });

 }

In addition, several methods are defined to facilitate external invocation (get text TextView, set text content directly), and also define a dip-pixel static method.

 Public TextView Gettextview () {return
 contentview;
 }

 public void SetText (Charsequence charsequence) {
 contentview.settext (charsequence);
 }

 public static int dip2px (context context, float Dipvalue) { 
 final float scale = context.getresources (). Getdisplaymetrics (). density;  
 return (int) (Dipvalue * scale + 0.5f); 
 } 

Actually here, our custom multi-text folding expansion Moretextview has been completed. How to use it?

Using in Layout/xx.xml

To easily define values using our just custom attributes, remember to define the application in the XML namespace:

Automatically referencing namespaces Res-auto
xmlns:more= "Http://schemas.android.com/apk/res-auto"
or directly define the package name
xmlns:more= "Http://schemas.android.com/apk/res/com.qiao.moretext"
The more that is behind the namespace you will use the beginning of the custom attribute.
Like our activity_main.xml.

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:more= "http:// Schemas.android.com/apk/res/com.qiao.moretext "
 android:id=" @+id/root "
 android:layout_width=" Match_ Parent "
 android:layout_height=" match_parent "
 android:background=" @android: Color/white "
 android:o rientation= "vertical" >

 <com.qiao.moretext.moretextview
 android:layout_width= "Match_parent"
 android:layout_height= "Wrap_content"
 android:layout_margin= "5dip" 
 more:textcolor= "@android: color/ Black "
 more:textsize=" 18dip "
 more:maxline=" 3 "
 more:text=" @string/content "/>

</ Linearlayout>

Directly define the use in Java
Because the top definition Moretextview only defines a construction method Moretextview (context context, AttributeSet attrs), it can only be used when using:

 Moretextview content = new Moretextview (mainactivity.this, null);
 Content.settext (GetText (r.string.content));
 Then addview to the place you want to add. of

course, as smart as you are, you definitely know how to define another construction method to be simple and practical.   
–> 
Moretextview (Context context) { 
//initializes Bindtextview () directly with default values 
(); 
}

3. Overview

In summary, we have completed the function to implement, as the UI, he may be a little bit shabby, but as a demo to play a role in the demonstration is enough. We might consider it as a listitem of Weibo, and add some features like dot-hop. Interested may wish to do a little bit.
Source Example Download Address: Http://xiazai.jb51.net/201610/yuanma/Androidtouchmove (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.