如何以编程方式在EditText上设置大小

时间:2014-09-16 12:38:06

标签: android android-edittext

我以编程方式创建了一个EditText。此EditText有一行,并添加到LinearLayout:

LinearLayout ll = (LinearLayout) myView.findViewById(R.id.select_options_option);
v = new EditText(context);
((EditText) v).setLines(1);
ll.addView(v);

我的问题是我只能在这个EditText中输入一个字符。如何设置EditText的宽度,以便输入3个或更多字符?

3 个答案:

答案 0 :(得分:3)

在添加TextView

之前,尝试将布局参数添加到线性布局中
LinearLayout ll = (LinearLayout) myView.findViewById(R.id.select_options_option);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.setLayoutParams(lp);
v = new EditText(context);
((EditText) v).setLines(1);
ll.addView(v)

您还可以在xml文件中添加WRAP_CONTENT

答案 1 :(得分:2)

如果您希望您的edittext匹配linearLayout的宽度

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                         LinearLayout.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(lp);

另外明智的是,如果你想宽度等于几个字符宽..

请参阅http://developer.android.com/reference/android/widget/TextView.html#setEms(int)

v.setEms(5);

答案 2 :(得分:0)

Try this too you can set EditText box height and width:

 LayoutParams lparams = new LayoutParams(60,30); // Width , height or (LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)
 EditText edittext = new EditText(this);
 edittext.setLayoutParams(lparams);