软键盘打开时调整滚动位置

che*_*psn 3 android android-layout

我在ScrollView中有一个表单.当我点击EditText时,软键盘出现,ScrollView滚动现在聚焦的EditText,以便它进入视图.

当前滚动行为

但是,我在EditText 下方提示信息,我也想显示,所以滚动应该更进一步,如下所示:

期望的滚动行为

EditText嵌入在表单元素中,实际上我想滚动到底部.我已经检查了ScrollView的源代码,它只会滚动到当前焦点视图的底部.也许有办法告诉ScrollView表单元素是当前关注的元素?

当然,我可以编写自己的ScrollView子类并覆盖滚动行为,但我想知道是否有更优雅的方法.

任何其他建议(调整滚动与固定偏移等)也是值得赞赏的.

che*_*psn 7

我还没有找到任何方法从外部配置ScrollView的滚动行为.所以我最终定义了我自己的ScrollView子类:`

/**
 * {@link ScrollView} extension that allows to configure scroll offset.
 */
public class ConfigurableScrollView extends ScrollView {

  private int scrollOffset = 0;

  public ConfigurableScrollView (final Context context, final AttributeSet attrs) {
    super(context, attrs);
  }

  public void setScrollOffset (final int scrollOffset) {
    this.scrollOffset = scrollOffset;
  }

  @Override
  protected int computeScrollDeltaToGetChildRectOnScreen (final Rect rect) {
    // adjust by scroll offset
    int scrollDelta = super.computeScrollDeltaToGetChildRectOnScreen(rect);
    int newScrollDelta = (int) Math.signum(scrollDelta) * (scrollDelta + this.scrollOffset);
    return newScrollDelta;
  }
}
Run Code Online (Sandbox Code Playgroud)

computeScrollDelta(...)除了之外,它是唯一可以作为覆盖目标的受保护方法onSizeChanged(...).

如果ScrollView确实认为需要滚动(例如,当键盘弹出时),上面示例中的signum函数可确保仅增加滚动.

我现在可以从外部设置一次额外的滚动偏移量,根据提示的高度计算.

使用扩展的ConfigurableScrollView而不是标准的ScrollView并不难,我只需要用新类的FQN替换ScrollView XML标签.