因为我一直在寻找这个,而我刚刚找到了一个解决方案,但这里没有,我将把它写在这里,以供将来参考。
注意:这段代码是直接从谷歌Android棒棒糖拨号器一段时间后,我不记得如果改变在当时。此外,我不知道这是在哪个许可证下,但我有理由认为它是Apache 2.0。
类ResizeTextView,实际的视图
public class ResizeTextView extends TextView {
private final int mOriginalTextSize;
private final int mMinTextSize;
private final static int sMinSize = 20;
public ResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mOriginalTextSize = (int) getTextSize();
mMinTextSize = (int) sMinSize;
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize);
}
这个ResizeTextView类可以扩展TextView和它所有的孩子,我的理解,所以EditText以及。
ViewUtil类带有resizeText方法(…)
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.graphics.Paint;
import android.util.TypedValue;
import android.widget.TextView;
public class ViewUtil {
private ViewUtil() {}
public static void resizeText(TextView textView, int originalTextSize, int minTextSize) {
final Paint paint = textView.getPaint();
final int width = textView.getWidth();
if (width == 0) return;
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, originalTextSize);
float ratio = width / paint.measureText(textView.getText().toString());
if (ratio <= 1.0f) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
Math.max(minTextSize, originalTextSize * ratio));
}
}
}
您应该将您的视图设置为
<yourpackage.yourapp.ResizeTextView
android:layout_width="match_parent"
android:layout_height="64dp"
android:gravity="center"
android:maxLines="1"/>
希望能有所帮助!