Ste*_*sen 5 android width android-edittext
我想为 an 设置最小固定宽度,EditText以便它既可以包含它的提示,也可以包含键入的、长度受限的内容,例如 2 位数字。
一些细节:
EditText类,但因为我复制应该处理EditText的Paint。我有这样做的实用方法,但它返回的宽度太窄,因此提示被剪裁。我究竟做错了什么?
EditText 在 XML 中指定如下:
<EditText
android:id="@+id/birthday_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="@string/birthday_month_hint"
android:lines="1"
android:maxLength="2">
Run Code Online (Sandbox Code Playgroud)
在我的活动中,我首先找到 EditText,然后使用Texts.setNiceAndTightWidth(monthEditText, 2)下面定义的(包括辅助方法)准备它:
public class Texts
{
public static void setNiceAndTightWidth ( EditText editText, int maxInputLength )
{
// String of chars to test for widest char. Include all possible input chars and chars of hint, as we need to make room for hint as well.
String testChars = String.format("1234568790%s", editText.getHint().toString());
char widestChar = getWidestChar(editText, testChars);
String widestString = repeat(widestChar, maxInputLength);
float widestStringWidth = getTextWidth(editText, widestString);
int width = (int)(widestStringWidth + 0.5f);
editText.setWidth(width);
// This was an experiment but it doesn't help.
ViewGroup.LayoutParams lp = editText.getLayoutParams();
lp.width = width;
editText.setLayoutParams(lp);
}
public static char getWidestChar ( TextView textView, String testChars )
{
float width, widest = 0;
char widestChar = '\0';
// Using Paint properties of TextView, including Fontface, text size, etc.
Paint paint = new Paint( textView.getPaint() );
for ( int i = 0 ; i < testChars.length() ; i++ ) {
width = paint.measureText(testChars, i, i+1);
if ( width > widest ) {
widest = width;
widestChar = testChars.charAt(i);
}
}
return widestChar;
}
public static String repeat ( char ch, int length )
{
char[] chars = new char[length];
Arrays.fill(chars, ch);
String string = String.valueOf(chars);
return string;
}
public static float getTextWidth ( TextView textView, CharSequence text )
{
Paint paint = new Paint( textView.getPaint() );
float width = paint.measureText(text, 0, text.length());
return width;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |