android - 更新背景边界

标签 android background android-custom-view

我正在尝试更新 EditText View 的背景边界,使最终结果类似于这样...

+----------------+
|  Empty Space   |
|                |
| +------------+ |
| | Background | |
| +------------+ |
+----------------+

我目前的做法是在onLayout中获取背景并简单地更新边界...

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  super.onLayout(changed, left, top, right, bottom);
  ...
  getBackground().setBounds(newLeft, newTop, newRight, newBottom);
}

但是,这根本不起作用。正在应用边界,但是当它绘制时,它不会改变。我最接近的是在 onDraw 中更改边界,但是,它最初会在其原始位置绘制,然后立即重新绘制到它的新位置......怎么可能我可以可靠地更改背景边界吗?

最佳答案

经过更多的研究,我能够解决这个问题的唯一方法是创建一个中介 Drawable(中间人)并将所有公共(public)方法委托(delegate)给实际的 Drawable。然后覆盖 setBounds 以设置我想要的任何值...

public class MyCustomView extends EditText {

  @Override
  public void setBackground(Drawable background) {
    super.setBackground(new IntermediaryDrawable(background));
  }

  ...

  private class IntermediaryDrawable extends Drawable {
    private Drawable theRealDrawable;

    public IntermediaryDrawable(Drawable source) {
      theRealDrawable = source;
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
      theRealDrawable.setBounds(left, 100, right, bottom);
    }

    ...
  }
}

相当hacky。如果有人遇到更好的解决方案,请分享。

关于android - 更新背景边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23400375/

相关文章:

android - 编译版本与最低要求版本 Android

iOS 一分钟内杀死在后台运行的 CallKit VoIP 应用程序

android - Android 中的 RenderScript 更加模糊

android - LinearLayout 作为自定义按钮,OnClickListener 从未调用

Android SQLite 没有按照我告诉它的顺序插入

android - native Activity OpenCV4Android 不工作

android - 从第三个 Activity 设置主 Activity 中的列表数据?

java - startDrag 方法已弃用,无法编译程序

css - 如何根据一侧的背景图像添加三 Angular 形边框(垂直)?

Android 默认文本选择器复制文本不起作用