简体   繁体   English

调整文字大小以适合Android中的按钮

[英]Adjust text size to fit button in Android

I have a number of buttons in a LinearLayout. 我在LinearLayout中有许多按钮。 The buttons have 1 weight, so they are placed evenly into the layout. 按钮有1个重量,因此它们均匀地放置在布局中。 I want to do something like this 我想做这样的事情

for (int i = 0; i < texts.size(); ++i) {
  Button button = new Button(/*context*/);
  button.setLayoutParams(/*WRAP_CONTENT, MATCH_PARENT, 1.0f*/)
  button.setText(texts[i]);
  float fontSize = 20.0f;
  button.setTextSize();
  while (textDoesNotFitIntoButton(button)) {
    fontSize -= 2.0f;
    button.setTextSize(fontSize);
  }
  linearLayout.addView(button);
}

How do I check if text does not fit into the button? 如何检查文本是否不适合按钮?

The point is to fill all the button with text in such a way, that text occupies all available space and gets neither truncated nor split into lines. 关键是用这样的方式用文本填充所有按钮,该文本占用所有可用空间,既不截断也不分割成行。

Eg String[] texts = new String[] { "0", "sin^-1" }; 例如String[] texts = new String[] { "0", "sin^-1" }; If I choose a single text size for "0" to occupy the whole space then I either get "sin" split into two lines "sin^" and "-1" or "0" appears smaller than it should. 如果我选择单个文本大小为“0”来占据整个空间,那么我要么将“sin”分成两行“sin ^”和“-1”或“0”看起来比它应该小。

I have edited the answer given by @Jaswanth Manigundan to make it extend from android.support.v7.widget.AppCompatButton. 我编辑了@Jaswanth Manigundan给出的答案,使其从android.support.v7.widget.AppCompatButton扩展。 Have a look at the below scripts: 看看下面的脚本:

FontFitTextView.java FontFitTextView.java

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;

public class FontFitTextView extends android.support.v7.widget.AppCompatButton
{
private static final float THRESHOLD = 0.5f;

private enum Mode { Width, Height, Both, None }

private int minTextSize = 1;
private int maxTextSize = 50;

private Mode mode = Mode.None;
private boolean inComputation;
private int widthMeasureSpec;
private int heightMeasureSpec;

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

public FontFitTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public FontFitTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray tAttrs = context.obtainStyledAttributes(attrs, R.styleable.FontFitTextView, defStyle, 0);
    maxTextSize = tAttrs.getDimensionPixelSize(R.styleable.FontFitTextView_maxTextSize, maxTextSize);
    minTextSize = tAttrs.getDimensionPixelSize(R.styleable.FontFitTextView_minTextSize, minTextSize);
    tAttrs.recycle();
}

private void resizeText() {
    if (getWidth() <= 0 || getHeight() <= 0)
        return;
    if(mode == Mode.None)
        return;

    final int targetWidth = getWidth();
    final int targetHeight = getHeight();

    inComputation = true;
    float higherSize = maxTextSize;
    float lowerSize = minTextSize;
    float textSize = getTextSize();
    while(higherSize - lowerSize > THRESHOLD) {
        textSize = (higherSize + lowerSize) / 2;
        if (isTooBig(textSize, targetWidth, targetHeight)) {
            higherSize = textSize;
        } else {
            lowerSize = textSize;
        }
    }
    setTextSize(TypedValue.COMPLEX_UNIT_PX, lowerSize);
    measure(widthMeasureSpec, heightMeasureSpec);
    inComputation = false;
}

private boolean isTooBig(float textSize, int targetWidth, int targetHeight) {
    setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    measure(0, 0);
    if(mode == Mode.Both)
        return getMeasuredWidth() >= targetWidth || getMeasuredHeight() >= targetHeight;
    if(mode == Mode.Width)
        return getMeasuredWidth() >= targetWidth;
    else
        return getMeasuredHeight() >= targetHeight;
}

private Mode getMode(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    if(widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY)
        return Mode.Both;
    if(widthMode == MeasureSpec.EXACTLY)
        return Mode.Width;
    if(heightMode == MeasureSpec.EXACTLY)
        return Mode.Height;
    return Mode.None;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if(!inComputation) {
        this.widthMeasureSpec = widthMeasureSpec;
        this.heightMeasureSpec = heightMeasureSpec;
        mode = getMode(widthMeasureSpec, heightMeasureSpec);
        resizeText();
    }
}

protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
    resizeText();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (w != oldw || h != oldh)
        resizeText();
}

public int getMinTextSize() {
    return minTextSize;
}

public void setMinTextSize(int minTextSize) {
    this.minTextSize = minTextSize;
    resizeText();
}

public int getMaxTextSize() {
    return maxTextSize;
}

public void setMaxTextSize(int maxTextSize) {
    this.maxTextSize = maxTextSize;
    resizeText();
}
}

style.xml: style.xml:

<resources>

<declare-styleable name="FontFitTextView">
    <attr name="minTextSize" format="dimension" />
    <attr name="maxTextSize" format="dimension" />
</declare-styleable>
</resources>

And in my activity_main.xml, I used the FontFitTextView tag instead of Button: 在我的activity_main.xml中,我使用了FontFitTextView标签而不是Button:

<com.example.myname.testsidebar.FontFitTextView
            android:id="@+id/userDetailsBtn"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:drawableTop="@drawable/user_details"
            android:gravity="center"
            android:background="#00FFFFFF"
            android:paddingTop="10sp"
            android:textSize="15sp"
            android:text="Your Details"
            android:drawableTint="#ED1B2F"
            android:textColor="#797369"
            android:layout_weight="1"
            android:layout_gravity="center"/>

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM