2011-03-26 19 views
1

テキストを縦に回転して印刷するTextViewのサブクラスを実装しようとしていますが、XMLレイアウトから指定した色でテキストを印刷するのに問題があります。クラスコードは次のとおりです。TextViewのサブクラスとテキストの色

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Rect; 
import android.text.TextPaint; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class VerticalTextView extends TextView { 
    private Rect bounds = new Rect(); 
    private TextPaint textPaint; 

    public VerticalTextView(Context context) { 
     super(context); 
    } 

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

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     textPaint = getPaint(); 
     textPaint.getTextBounds((String) getText(), 0, getText().length(), bounds); 
     setMeasuredDimension((int) (bounds.height() + textPaint.descent()), bounds.width()); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     canvas.rotate(-90, bounds.width(), 0); 
     canvas.drawText((String) getText(), 0, -bounds.width() + bounds.height(), textPaint); 
    } 
} 

私はこのビューのカスタムプロパティの必要がないので、私はそれのためにstyleableを宣言していませんよ。あなたが見ることができるように、私はテキストの色(青)とテキストスタイル(イタリック)の両方を指定してい

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <com.verticaltextview.VerticalTextView 
     android:layout_width="wrap_content" android:layout_height="wrap_content" 
     android:text="Hello World" android:textColor="#ff0000ff" 
     android:textStyle="italic" /> 
</LinearLayout> 

が、唯一:

私はこのレイアウトで私の活動でこのビューを使用していますテキストは黒で印刷されるため、スタイルが適用されます。 onDraw()メソッドで、textPaint.setColor(0xff00ff00)を実行して色をハードコードすると、テキストは正しく色で印刷されます。

提案?その後、textPaintにこの色を設定

**public VerticalTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
}** 

:;おかげで)

+0

RGB android:textColor = "#0000FF"を試してみると、アルファチャンネルを宣言する必要はありません – Blundell

答えて

1

次のおVerticalTextViewのコンストラクタを変更する必要があります。

private int   col  = 0xFFFFFFFF; 

public VerticalTextView(Context context, AttributeSet attrs) 
{ 
    super(context, attrs); // was missing a parent 
    col = getCurrentTextColor(); 
} 

次に、あなたのonDraw()機能に

textPaint.setColor(col); 

を追加します。

これが役に立ちます。

+0

XML属性をsuperに渡すコンストラクタは、テキストカラーxml atributeを処理しますか? – Blundell

+0

あなたはそうです、Blundell。私はずっと簡単な答えを修正しました:) ...それを指摘してくれてありがとう。 – rajath

+0

これはうまくいきましたが、なぜペイントの色をこのように設定する必要がありますか?それは 'スーパー'コンストラクタによって自動的に行われるべきではありませんか? – Venator85

0

私はあなたが色を得ることができると思います。

関連する問題