該解決方案確實覆蓋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;
}
你最終會看到一個帶有摘要文本的漂亮的單選按鈕。可能會有問題,但有多行文本和摘要。這種意義上的改進意見值得歡迎。