Toolbar title添加滚动效果

Toolbar的初始化

在toolbar 的初始化工程中,我们通常会使用一下方式:

toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar == null) {
            return;
        }
        setSupportActionBar(toolbar)

而对于标题的初始化:

getSupportActionBar().setTitle("");

toolbar 添加自动滚动效果

通过java反射的方式获取Toolbar 中的成员属性。

public class ToolbarUtils {
    public static TextView getToolbarTitleView(Toolbar toolbar) {

        try {

            Field field = toolbar.getClass().getDeclaredField("mTitleTextView");
            field.setAccessible(true);

            Object object = field.get(toolbar);
            if (object !=null) {
                TextView mTitleTextView = (TextView) object;
                return mTitleTextView;
            }
            Ln.d("toolbarUtils :" + "mTitleTextView do not find");
        } catch (IllegalAccessException e) {
            Ln.d("toolbarUtils :" + "IllegalAccessException");
        } catch (NoSuchFieldException e) {
            Ln.d(e);
        }catch (Exception e) {
            Ln.d("toolbarUtils :" + "paser error");
        }
        return null;
    }

    public static void setMarqueeForToolbarTitleView(final Toolbar toolbar) {
        toolbar.post(new Runnable() {
            @Override
            public void run() {
                TextView mTitleTextView = getToolbarTitleView(toolbar);
                if (mTitleTextView == null) {
                    Ln.d("toolbarUtils :" + "mTitleTextView is null");
                    return;
                }
                mTitleTextView.setHorizontallyScrolling(true);
                mTitleTextView.setMarqueeRepeatLimit(-1);
                mTitleTextView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
                mTitleTextView.setSelected(true);
                Ln.d("toolbarUtils :" + "mTitleTextView set successfully ");
            }
        });

    }
}

你可能感兴趣的:(Toolbar title添加滚动效果)