Primera letra en mayúsculas para EditText


Estoy trabajando en una pequeña aplicación de lista de tareas personales y hasta ahora todo ha estado funcionando bastante bien. Hay una pequeña peculiaridad que me gustaría averiguar. Cada vez que voy a agregar un nuevo elemento, tengo un Diálogo con una vista EditText que se muestra dentro. Cuando selecciono la vista EditText, el teclado aparece para ingresar texto, como debería. En la mayoría de las aplicaciones, el valor predeterminado parece ser que la tecla mayús se mantiene para la primera letra... aunque no lo hace por mi opinión. Tiene que haber una manera sencilla arreglo, pero he buscado la referencia repetidamente y no puedo encontrarla. Estoy pensando que tiene que haber un atributo xml para la referencia cargada por el Adaptador, pero no puedo averiguar qué es.

Author: MiguelHincapieC, 2011-01-26

11 answers

Estáticamente (es decir, en su archivo XML de diseño): establezca android:inputType="textCapSentences" en su EditText.

Programáticamente: usted tiene que incluir InputType.TYPE_CLASS_TEXT en el InputType de la EditText, por ejemplo,

EditText editor = new EditText(this); 
editor.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

Se puede combinar con texto y sus variaciones para solicitar la capitalización del primer carácter de cada oración.

- Google Docs

 727
Author: McStretch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-16 06:40:33

Simplemente use android:inputType="textCapWords" en su elemento EditText.

Por ejemplo:

<EditText
    android:id="@+id/txtName"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_weight="0.7"
    android:inputType="textCapWords"
    android:textColorHint="#aaa"
    android:hint="Name Surname"
    android:textSize="12sp" />

Consulte el siguiente enlace para consultar: http://developer.android.com/reference/android/widget/TextView.html#attr_android%3ainputType

 62
Author: Mangi Morobe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 04:33:51
testEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);   

O android:inputType="textCapSentences" solo funcionará Si la Configuración de Mayúscula automática del teclado del dispositivo está habilitada.

 25
Author: Lakshmanan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-16 18:13:20

Aplique la siguiente línea en su EditText en XML.

android:inputType="textCapSentences|textMultiLine"

También permitirá el soporte multilínea.

 19
Author: Shivang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-05 15:57:44

Me encontré con el mismo problema, simplemente compartiendo lo que descubrí. Podría ayudarte a ti y a otros...

Pruebe esto en su diseño.agregue la línea de abajo en su EditText.

android:inputType="textCapWords|textCapSentences"

Funciona bien en mí.. espero que funcione también en ti...

 14
Author: user4144348,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-29 12:16:35

Establecer el tipo de entrada en XML, así como en el archivo JAVA de esta manera,

En XML,

Android: inputType= "textMultiLine / textCapSentences"

También permitirá multilínea y en el archivo JAVA,

edittext.setRawInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

Asegúrese de que la configuración de Mayúsculas automáticas de su teclado estéhabilitada .

 1
Author: Siddharth Sheth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-15 11:21:45

Puedo asegurarle que ambas respuestas harán que la primera letra sea mayúscula y no harán que edittext sea una sola línea.

Si desea hacerlo en XMl a continuación se muestra el código

android:inputType="textCapWords|textCapSentences"

Si quieres hacerlo en activity / fragment etc a continuación está el código

momentTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_MULTI_LINE)

PD: Si no tiene otra propiedad también puede agregarla fácilmente con un símbolo de tubería"|", solo asegúrese de que no haya espacio en xml entre las propiedades del atributo

 1
Author: Tushar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-20 17:03:40

En su archivo XML de diseño: establecer android: inputType= "textCapSentences" en tu EditText para tener el primer alfabeto de la primera palabra de cada oración como capital O android: inputType= "textCapWords" en tu EditText para tener el primer alfabeto de cada palabra como capital

 1
Author: Himmat Gill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-20 18:48:41

Pruebe Este Código, pondrá en mayúscula el primer carácter de todas las palabras.

- establecer addTextChangedListener para EditText view

Edt_text.Por lo tanto, no es necesario]}

- Añadir TextWatcher

TextWatcher watcher = new TextWatcher() {
    int mStart = 0;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mStart = start + count;
    }

    @Override
    public void afterTextChanged(Editable s) {
        String input = s.toString();
        String capitalizedText;
        if (input.length() < 1)
            capitalizedText = input;
        else if (input.length() > 1 && input.contains(" ")) {
            String fstr = input.substring(0, input.lastIndexOf(" ") + 1);
            if (fstr.length() == input.length()) {
                capitalizedText = fstr;
            } else {
                String sstr = input.substring(input.lastIndexOf(" ") + 1);
                sstr = sstr.substring(0, 1).toUpperCase() + sstr.substring(1);
                capitalizedText = fstr + sstr;
            }
        } else
            capitalizedText = input.substring(0, 1).toUpperCase() + input.substring(1);

        if (!capitalizedText.equals(edt_text.getText().toString())) {
            edt_text.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    edt_text.setSelection(mStart);
                    edt_text.removeTextChangedListener(this);
                }
            });
            edt_text.setText(capitalizedText);
        }
    }
};
 0
Author: Dharmesh Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-29 12:33:10

Antes solía ser android:capitalize="words", que ahora está en desuso. La alternativa recomendada es utilizar android:inputType="textCapWords"

Tenga en cuenta que esto solo funcionará si la configuración de Mayúsculas automáticas del teclado de su dispositivo está habilitada.

Para hacer esto programáticamente, use el siguiente método:

setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);

 0
Author: Mahendra Liya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-27 06:14:41

Utilice este código solo para mayúsculas de Primera letra para EditText

MainActivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:tag="true">
    </EditText>

</RelativeLayout>

MainActivity.java

EditText et = findViewById(R.id.et);
        et.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                if (et.getText().toString().length() == 1 && et.getTag().toString().equals("true"))
                {
                    et.setTag("false");
                    et.setText(et.getText().toString().toUpperCase());
                    et.setSelection(et.getText().toString().length());
                }
                if(et.getText().toString().length() == 0)
                {
                    et.setTag("true");
                }
            }

            public void afterTextChanged(Editable editable) {

            }
        });
 0
Author: milan pithadia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-16 08:46:27