android - 如何使用 Instagram 的 "TextLayoutView"改进 Android 上的 TextView 渲染

标签 android textview rendering instagram

为了改进 Instagram 中的 TextView 渲染,Instagram 的工程师在 here 中提供了一个 hack ,他们使用自定义 View (TextLayoutView)来缓存text.Layout,但是在这篇文章中,他们没有给我们演示或告诉我们如何使用它,所以如果我想使用这个hack,我该怎么做?

最佳答案

这是我的简单实现:

TextLayoutView:

public class TextLayoutView extends View {

private Layout mLayout;

public TextLayoutView(Context context) {
    this(context, null);
}

public TextLayoutView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public TextLayoutView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    setFocusable(true);
}

@Override
protected void onDraw(Canvas canvas) {
    long t1=System.currentTimeMillis();
    super.onDraw(canvas);
    canvas.save();
    if (mLayout != null) {
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mLayout.draw(canvas);
    }

    canvas.restore();
    long t2=System.currentTimeMillis();
    Log.i("TEST", "onDraw::"+(t2-t1));
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    long t1=System.currentTimeMillis();
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (mLayout != null) {
        setMeasuredDimension(
                getPaddingLeft() + getPaddingRight() + mLayout.getWidth(),
                getPaddingTop() + getPaddingBottom() + mLayout.getHeight());
    }
    long t2=System.currentTimeMillis();
    Log.i("TEST", "onMeasure::"+(t2-t1));
}


public void setTextLayout(Layout layout) {
    mLayout = layout;
    requestLayout();
}}

你可以这样使用它:

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    ......
    viewHolder.textView.setTextLayout(getLayout(mList.get(position)));
    return convertView;
}
    private final Map<String, Layout> mLayoutMap = new ConcurrentHashMap<String, Layout>();
private Layout getLayout(String str) {
    Layout layout = mLayoutMap.get(str);
    if (layout == null) {
        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(20);
        layout = new StaticLayout(str, textPaint, width, Alignment.ALIGN_CENTER,
                1.0f, 0.0f, true);
        mLayoutMap.put(str, layout);
    }
    return layout;
}

关于android - 如何使用 Instagram 的 "TextLayoutView"改进 Android 上的 TextView 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860276/

相关文章:

android - 将 Context.MODE_MULTI_PROCESS 提供给 getSharedPreferences() 是否使共享首选项线程安全?

android - TextView 中间有椭圆导致 "ArrayIndexOutOfBoundsException"异常

email - Outlook 2007 HTML电子邮件呈现错误(水平空白)需要解决方法

jsf - JSF 中的条件渲染

c++ - 在图形管道中的哪个阶段进行剪辑?

android - 从 sdcard 将图像文件读入位图,为什么会出现 NullPointerException?

android - 从编辑文本字符串中删除空格

安卓文件选择器

android - 在 TextView 中垂直对齐由 HTML 定义的图像

android - TextView 中的项目符号点被截断