如何为RadioButton添加类似Preference的摘要信息?

3
我想在我的RadioButton上添加一个类似于CheckBoxPreference的摘要。

GPS satellites checkbox

我试图扩展RadioButton并覆盖onDraw方法,但我卡在了所有计算上,以使其布局得体。

@Override
protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  Paint paint = new Paint();
  int textSize = 20;
  int horizontalStartPosition = getCompoundPaddingLeft() + getCompoundDrawablePadding();
  int verticalStartPosition = getBaseline() + getLineHeight();
  paint.setTextSize(textSize);
  paint.setColor(Color.GRAY);
  paint.setAntiAlias(true);
  canvas.drawText(summary, horizontalStartPosition, verticalStartPosition, paint);
}

这将呈现出类似于以下内容:

带有摘要的单选按钮

这样做真的是正确的方式吗(感觉不是),还是我应该尝试完全不同的方法?

1个回答

3
解决方案确实是重写 onDraw 方法。以下是我最终的实现方式。
在构造函数中获取摘要文本的正确样式属性。
public SummaryRadioButton(Context context, AttributeSet attrs) {
  super(context, attrs);
  TypedArray a = getContext().getTheme()
    .obtainStyledAttributes(
      attrs,
      new int[] { android.R.attr.textSize,
        android.R.attr.textColor },
      android.R.attr.textAppearanceSmall, 0);
  textSize = a.getDimensionPixelSize(0, 15);
  textColor = a.getColorStateList(1);
  paint = new Paint(getPaint());
  paint.setTextSize(textSize);
  a.recycle();
}

onDraw中获取行高和基线的垂直位置,并计算摘要文本的正确起始点。根据单选按钮状态使用正确的文本颜色。

@Override
protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  if (summary != null && summary.length() > 0) {
    int horizontalStartPosition = getCompoundPaddingLeft()
        + getCompoundDrawablePadding();
    int verticalStartPosition = getBaseline() + getLineHeight();

    paint.setColor(textColor.getColorForState(getDrawableState(), 0));
    canvas.drawText((String) summary, horizontalStartPosition,
        verticalStartPosition, paint);
  }
}

在调用setSummary方法时,在文本末尾添加一个额外的换行符。这可能有点取巧,但我找不到更好的办法让超类正确定位文本。

public void setSummary(CharSequence summary) {
  if (summary != null && summary.length() > 0) {
    setText(getText() + "\n");
  } else {
    setText(getText());
  }
  if (summary == null && this.summary != null || summary != null
      && !summary.equals(this.summary)) {
    this.summary = summary;
  }
}

因此,我们需要覆盖 getText 方法,并在摘要存在时删除换行符。
@Override
@CapturedViewProperty
public CharSequence getText() {
  CharSequence text = super.getText();
  if (summary != null && summary.length() > 0) {
    text = text.subSequence(0, text.length() - 1);
  }
  return text;
}

您将会得到一个外观漂亮的单选按钮及其摘要文本。然而,对于多行文本和摘要,可能会存在问题。欢迎提出改进建议。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接