Marquee title in Toolbar / ActionBar in Android with Lollipop SDK?
Get the title TextView
object from declared field name of TextView
in Toolbar
class and Marquee title of toolbar.
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(toolbar);
titleTextView.setEllipsize(TruncateAt.MARQUEE);
titleTextView.setFocusable(true);
titleTextView.setFocusableInTouchMode(true);
titleTextView.requestFocus();
titleTextView.setSingleLine(true);
titleTextView.setSelected(true);
titleTextView.setMarqueeRepeatLimit(-1);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
Kotlin solution to set MARQUEE
for both Title and Subtitle TextViews (it just finds all TextViews inside Toolbar):
findViewById<Toolbar>(R.id.action_bar)?.let {
setToolbarTextViewsMarquee(it)
}
fun setToolbarTextViewsMarquee(toolbar: Toolbar) {
for (child in toolbar.children) {
if (child is TextView) {
setMarquee(child)
}
}
}
fun setMarquee(textView: TextView) {
textView.ellipsize = TextUtils.TruncateAt.MARQUEE
textView.isSelected = true
textView.marqueeRepeatLimit = -1
}
So it's not necessary to add Toolbar view (android.support.v7.widget.Toolbar
or androidx.appcompat.widget.Toolbar
) to xml layout
You can use the default Toolbar which AppCompat theme automatically adds:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
Try to put a TextView inside the Toolbar:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize" >
<TextView
android:id="@+id/toolbar_title"
android:text="This will run the marquee animation forever"
android:textSize="@dimen/abc_text_size_title_material_toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true" />
</android.support.v7.widget.Toolbar>
And then, use the Toolbar as an ActionBar and clear/disable its title:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null); // or, setDisplayShowTitleEnabled(false)