简体   繁体   中英

How set size on an EditText programmatically

I have created an EditText programmatically. This EditText has one line and is added to a LinearLayout:

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

My problem is that I can only type one character in this EditText. How can I set the width of an EditText, so that I can type in 3 or more charaters?

Try adding layout parameters to the linear layout before adding the 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)

You can also add the WRAP_CONTENT in your xml file

If you want your edittext to match the width of linearLayout

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

other wise if you want width to be equal to few character wide..

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

v.setEms(5);
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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