2013-01-09 66 views
3

我想在我的RadioButton中有一個總結,有點像CheckBoxPreference如何添加喜歡類似的摘要到RadioButton?

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); 
} 

這使得這樣的事情:

RadioButton with summary

這真的是要走的路(不覺得它是)或者我應該嘗試完全不同的東西?

回答

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; 
} 

你最終會看到一個帶有摘要文本的漂亮的單選按鈕。可能會有問題,但有多行文本和摘要。這種意義上的改進意見值得歡迎。

相關問題