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

wqy*_*csu 5 android rendering textview instagram

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

ads*_*ion 3

这是我的简单实现\xef\xbc\x9a

\n\n

TextLayoutView\xef\xbc\x9a

\n\n
public class TextLayoutView extends View {\n\nprivate Layout mLayout;\n\npublic TextLayoutView(Context context) {\n    this(context, null);\n}\n\npublic TextLayoutView(Context context, AttributeSet attrs) {\n    this(context, attrs, 0);\n}\n\npublic TextLayoutView(Context context, AttributeSet attrs, int defStyleAttr) {\n    super(context, attrs, defStyleAttr);\n    setFocusable(true);\n}\n\n@Override\nprotected void onDraw(Canvas canvas) {\n    long t1=System.currentTimeMillis();\n    super.onDraw(canvas);\n    canvas.save();\n    if (mLayout != null) {\n        canvas.translate(getPaddingLeft(), getPaddingTop());\n        mLayout.draw(canvas);\n    }\n\n    canvas.restore();\n    long t2=System.currentTimeMillis();\n    Log.i("TEST", "onDraw::"+(t2-t1));\n}\n\n@Override\nprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n    long t1=System.currentTimeMillis();\n    super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n    if (mLayout != null) {\n        setMeasuredDimension(\n                getPaddingLeft() + getPaddingRight() + mLayout.getWidth(),\n                getPaddingTop() + getPaddingBottom() + mLayout.getHeight());\n    }\n    long t2=System.currentTimeMillis();\n    Log.i("TEST", "onMeasure::"+(t2-t1));\n}\n\n\npublic void setTextLayout(Layout layout) {\n    mLayout = layout;\n    requestLayout();\n}}\n
Run Code Online (Sandbox Code Playgroud)\n\n

你可以这样使用它:

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