2014-01-18 2 views
1

Я хочу, чтобы текст внутри моего TextView соответствовал экрану. Мне нужно реализовать что-то вроде этого:Текст внутри TextView подходит к экрану

enter image description here

Буква «А» должна быть в центре экрана с высотой, равной высоте экрана устройства. Я создал Custom TextView для этого следующим образом, но это, похоже, не работает. Я имею в виду, что мой текст (буква А) не соответствует высоте экрана. Я попытался вручную настроить размер шрифта текста, но это не так, как я предполагаю. Может ли кто-нибудь указать на лучшее решение для этого?

package com.example; 

import android.content.Context; 
import android.content.res.TypedArray; 

import android.graphics.Paint; 
import android.graphics.Rect; 
import android.util.AttributeSet; 
import android.util.TypedValue; 
import android.widget.TextView; 

public class FontFitTextView extends TextView 
    { 
    private Paint mTestPaint; 
    private float maxFontSize; 
    private static final float MAX_FONT_SIZE_DEFAULT_VALUE = 20f; 

    public FontFitTextView(Context context) 
    { 
     super(context); 
     initialise(context, null); 
    } 

    public FontFitTextView(Context context, AttributeSet attributeSet) 
    { 
    super(context, attributeSet); 
    initialise(context, attributeSet); 
    } 

public FontFitTextView(Context context, AttributeSet attributeSet, int defStyle) 
{ 
    super(context, attributeSet, defStyle); 
    initialise(context, attributeSet); 
} 

private void initialise(Context context, AttributeSet attributeSet) 
{ 
    if(attributeSet!=null) 
    { 
     TypedArray styledAttributes = context.obtainStyledAttributes(attributeSet, R.styleable.FontFitTextView); 
     maxFontSize = styledAttributes.getDimension(R.styleable.FontFitTextView_maxFontSize, MAX_FONT_SIZE_DEFAULT_VALUE); 
     styledAttributes.recycle(); 
    } 
    else 
    { 
     maxFontSize = MAX_FONT_SIZE_DEFAULT_VALUE; 
    } 

    mTestPaint = new Paint(); 
    mTestPaint.set(this.getPaint()); 
    //max size defaults to the initially specified text size unless it is too small 
} 

private void refitText(String text, int textWidth, int textHeight) 
{ 
    if (textWidth <= 0) 
     return; 
    int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight(); 
    int targetHeight = textHeight - this.getPaddingTop() - this.getPaddingBottom(); 
    float hi = maxFontSize; 
    float lo = 2; 
    final float threshold = 1f; // How close we have to be 

    mTestPaint.set(this.getPaint()); 

    Rect bounds = new Rect(); 

    while ((hi - lo) > threshold) 
    { 
     float size = (hi + lo)/2; 
     mTestPaint.setTextSize(size); 

     mTestPaint.getTextBounds(text, 0, text.length(), bounds); 

     if (bounds.width() >= targetWidth || bounds.height() >= targetHeight) 
      hi = size; // too big 
     else 
      lo = size; // too small 

    } 
    // Use lo so that we undershoot rather than overshoot 
    this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo); 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
{ 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 
    int height = getMeasuredHeight(); 
    refitText(this.getText().toString(), parentWidth, height); 
    this.setMeasuredDimension(parentWidth, height); 
} 

@Override 
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) 
{ 
    refitText(text.toString(), this.getWidth(), this.getHeight()); 
} 

@Override 
protected void onSizeChanged(int w, int h, int oldw, int oldh) 
{ 
    if (w != oldw) 
    { 
     refitText(this.getText().toString(), w, h); 
    } 
    } 
} 

XML файл

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:res-auto="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/home_Layout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

<LinearLayout 
    android:id="@+id/linear1" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_vertical"> 

    <com.example.FontFitTextView 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:text="1" 
     android:textSize="80sp" 
     res-auto:maxFontSize="55sp" /> 

</LinearLayout> 

</RelativeLayout> 
+0

«Но это, похоже, не работает». «Не могли бы вы рассказать об этом? – csmckelvey

+0

Я редактировал вопрос. в основном мне нужно текст внутри текстового поля, чтобы он соответствовал высоте экрана. В настоящее время он не соответствует высоте экрана устройства –

ответ

1

Попробуйте вызвать super.onMeasure() метод в конце onMeasure() метода с обновленной ширины и высоты (parentWidth, высота).

+0

Привет, Нареш, я пробовал это ... но тогда я не вижу текст на экране. :( –

+0

Попробуйте отрегулировать значение ширины и высоты, прежде чем вы вызовете метод super. Это значение, которое вы передаете методу супер, - это тот, который определяет ширину и высоту. Значения, которые у вас были в parentWidth и height, могут быть слишком маленькими или слишком большой, попытайтесь исследовать и исследовать его. –

+0

Привет, при отладке с использованием операторов Log в Android, я получаю parentWidth как 480 и высоту как 0 –

Смежные вопросы