Monday, 26 May 2014

Android - Hide and show textView

In android, when a text is quite big, it could be hidden and when you click on it, show the text.

1. Hide
To hide the text, the easier way is by using the attribute MaxLines and ellipsize to the end.
<TextView
    android:id="@+id/completeDescriptionTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:maxLines="3"
    android:ellipsize="end"
/>

2. Show
Once the text has been hidden, if by any action of the user you wan to show the entire text, you should do the follow:

TextView completeDescriptionTextView = (TextView)findViewbyid(R.id.completeDescriptionTextView);
completeDescriptionTextView.setMaxLines(Integer.MAX_VALUE);
// The ellipsize must be set as null for android 2.3                                                          
completeDescriptionTextView.setEllipsize(null);
expandCompleteDescriptionTextView.setVisibility(View.GONE);
break;

3. Extra
In order to detect if the textview has been ellipsized, this works:
private boolean hasBeenEllipsized(TextView textView) {
    Layout layout = completeDescriptionTextView.getLayout();
    // If it contains layouts                                                                                                     
    if (layout != null) {
        int lines = layout.getLineCount();
        // Check if it contains text                                                                                                      
        if (lines > 0) {
            // Check if the last line has been elipsized                                                                                  
            if (layout.getEllipsisCount(lines-1) > 0)
                return true;
            }
        }
        return false;
    }
}

Source:
StackOverFlow - How to reset Android textview Maxlines
StackOverFlow - Check if textview is ellipsized in android

No comments:

Post a Comment