VansFannel
VansFannel

Reputation: 45961

How to set editText width to one character

I'm developing an Android application and now I'm creating a password screen which will have four editText to hold four digits.

This is my password.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/firstNum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="14dp"
        android:layout_marginTop="191dp"
        android:ems="10"
        android:inputType="textPassword"
        android:lines="1"
        android:maxLength="1"
        android:maxLines="1"
        android:minLines="1" >

        <requestFocus />
    </EditText>

</RelativeLayout>

And this is what I get:

enter image description here

But the editText is too big.

How can I change its width to fit it to one character only?

Upvotes: 3

Views: 8432

Answers (3)

Ken Wolf
Ken Wolf

Reputation: 23279

Change it to android:ems="1"

<EditText
    android:id="@+id/firstNum"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="14dp"
    android:layout_marginTop="191dp"
    android:ems="1"
    android:inputType="textPassword"
    android:lines="1"
    android:maxLength="1"
    android:maxLines="1"
    android:minLines="1" >

http://developer.android.com/reference/android/R.attr.html#ems

An "em" is a term from typography - basically you can think of it as the width of 1 character at the specified font size. This is preferred as it will always be one character wide even if you change the font size.

http://en.wikipedia.org/wiki/Em_(typography)

Upvotes: 18

prvn
prvn

Reputation: 916

set android:maxEms="1" or remove wrap_content and set the width

android:layout_width="40dp"
android:layout_height="40dp"

Upvotes: 0

karan
karan

Reputation: 8853

If you want to set physical your edittext's physical width you can use

android:maxWidth="your size in dp"

but if you want to receive single character in it you can use

android:maxLength="1"

Upvotes: -2

Related Questions