Skip to content

Instantly share code, notes, and snippets.

@jandrop
Forked from InsanityOnABun/MarqueeToolbar.java
Created March 17, 2016 11:00
Show Gist options
  • Select an option

  • Save jandrop/0dcf8a91acad17fad73f to your computer and use it in GitHub Desktop.

Select an option

Save jandrop/0dcf8a91acad17fad73f to your computer and use it in GitHub Desktop.

Revisions

  1. @InsanityOnABun InsanityOnABun created this gist Jan 4, 2015.
    68 changes: 68 additions & 0 deletions MarqueeToolbar.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    import android.content.Context;
    import android.support.v7.widget.Toolbar;
    import android.text.TextUtils;
    import android.util.AttributeSet;
    import android.widget.TextView;

    import java.lang.reflect.Field;

    public class MarqueeToolbar extends Toolbar {

    TextView title;

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

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

    public MarqueeToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    }

    @Override
    public void setTitle(CharSequence title) {
    if (!reflected) {
    reflected = reflectTitle();
    }
    super.setTitle(title);
    selectTitle();
    }

    @Override
    public void setTitle(int resId) {
    if (!reflected) {
    reflected = reflectTitle();
    }
    super.setTitle(resId);
    selectTitle();
    }

    boolean reflected = false;
    private boolean reflectTitle() {
    try {
    Field field = Toolbar.class.getDeclaredField("mTitleTextView");
    field.setAccessible(true);
    title = (TextView) field.get(this);
    title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    title.setMarqueeRepeatLimit(-1);
    return true;
    } catch (NoSuchFieldException e) {
    e.printStackTrace();
    return false;
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    return false;
    } catch (NullPointerException e) {
    e.printStackTrace();
    return false;
    }
    }

    public void selectTitle() {
    if (title != null)
    title.setSelected(true);
    }
    }