【问题标题】:How to get a reference to the layout from within a custom TextView如何从自定义 TextView 中获取对布局的引用
【发布时间】:2015-02-26 12:46:17
【问题描述】:

这可能是一个容易回答的问题,但搜索只是出现了诸如膨胀和 xml 布局之类的东西,这不是我想要的。

我有一个要在其上绘制光标的自定义 TextView。 (我不能使用 EditText。)为了画线,我需要根据光标应该在的字符偏移量计算各种坐标。我尝试了以下作为自定义 TextView 的方法:

public void setCursorLocation(int characterOffset) {

    Layout layout = this.getLayout();

    int line = layout.getLineForOffset(characterOffset);
    mCursorX = layout.getPrimaryHorizontal(characterOffset);
    mCursorBaseY = layout.getLineBaseline(line);
    mCursorBottomY = layout.getLineBottom(line);
    mCursorAscentY = layout.getLineAscent(line);
}

但是,布局为空。我什至尝试将 TextView 作为参数传递,但布局仍然为空。我做错了什么?

public void setCursorLocation(View view, int characterOffset) {

    Layout layout = ((TextView) view).getLayout();

    ...
}

更新

我改成下面这个了

public void setCursorLocation(Layout layout, int characterOffset) {

但即使那个布局也是空的。然后我查看了我在主要活动中调用它的位置:

inputWindow.setText(displayText);
inputWindow.setCursorLocation(inputWindow.getLayout(), glyphCurosrPosition);

观察表达式inputWindow.getLayout() 很好,直到setText 被调用,然后突然它变成了null。我想那是因为它自己失效了。那么我如何/何时绘制光标?我的猜测是发布一个runnable也许。 更新 2 是的,见下文。

【问题讨论】:

  • 尝试获取视图的父级,getParent();

标签: java android layout textview


【解决方案1】:

这个解决方案终于对我有用了。

来自主要活动:

inputWindow.setText(displayText);
inputWindow.post(new Runnable() {

    @Override
    public void run() {

        inputWindow.setCursorLocation(glyphCursorPosition);
    }

});

在自定义TextView中:

public void setCursorLocation(int characterOffset) {

    Layout layout = this.getLayout();

    int line = layout.getLineForOffset(characterOffset);
    mCursorX = layout.getPrimaryHorizontal(characterOffset);
    mCursorBaseY = layout.getLineBaseline(line);
    mCursorBottomY = layout.getLineBottom(line);
    mCursorAscentY = layout.getLineAscent(line);

    this.invalidate();
}

缺点是在光标自行更新之前会有一点时间延迟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多