Android: TextView with Ellipsis Listener

I created an extension of the Android TextView component to adds the ability to receive updates when the text has an ellipses added. Short and sweet, here is the code and the link for the gist:

/**
 * Author: Michael Ritchie, ThanksMister LLC
 * Date: 10/16/12
 * Web: thanksmister.com
 *
 * Extension of <code>TextView</code> that adds listener for ellipses changes.  This can be used to determine
 * if a TextView has an ellipses or not.
 *
 * Derived from discussion on StackOverflow:
 *
 * http://stackoverflow.com/questions/4005933/how-do-i-tell-if-my-textview-has-been-ellipsized
 */
package com.cg.mobile.components;

import android.content.Context;
import android.text.Layout;
import android.util.AttributeSet;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class EllipsisTextView extends TextView
{
    public interface EllipsisListener
    {
        void ellipsisStateChanged(boolean ellipses);
    }

    private final List<EllipsisListener> ellipsesListeners = new ArrayList<EllipsisListener>();

    private boolean ellipses;

    public EllipsisTextView(Context context)
    {
        super(context);
    }

    public EllipsisTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public EllipsisTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public void addEllipsesListener(EllipsisListener listener)
    {
        if (listener == null) {
            throw new NullPointerException();
        }
        ellipsesListeners.add(listener);
    }

    public void removeEllipsesListener(EllipsisListener listener)
    {
        ellipsesListeners.remove(listener);
    }

    public boolean hadEllipses() {
        return ellipses;
    }

    @Override
    public void layout(int l, int t, int r, int b)
    {
        super.layout(l, t, r, b);

        ellipses = false;
        Layout layout = getLayout();
        if ( layout != null){
            int lines = layout.getLineCount();
            if ( lines > 0)  {
                if ( layout.getEllipsisCount(lines-1) > 0) {
                    ellipses = true;
                }
            }
        }

        for (EllipsisListener listener : ellipsesListeners) {
            listener.ellipsisStateChanged(ellipses);
        }
    }
}

Gist: https://gist.github.com/3902660

-Mr

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s