EditText: Sugerencia del centro pero ha entrado el texto desde arriba

Hola tengo un texto de edición con la pista, he hecho la pista como medio usando android:gravity:"center" . Cuando empiezo a escribir en el edittext el mecanografiado está comenzando desde el centro, cómo hacer el mecanografiar comienzo de leftcorner mientras que la indirecta sigue centrada

 <EditText android:id="@+id/edittext" android:layout_width="230dp" android:layout_height="110dp" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" android:layout_marginLeft="5dp" android:layout_marginTop="33dp" android:layout_toLeftOf="@+id/relativeLayout1" android:background="@drawable/roundcorners" android:ems="10" android:gravity="center_horizontal" android:hint="@string/fbhint" android:lines="6" android:paddingRight="5dp" android:textSize="14sp" android:windowSoftInputMode="stateHidden" /> 

Por defecto android EditText tiene gravedad central. Sólo hazlo android:gravity="top|left"

También no hay ningún atributo especial para hacer una pista en el centro y el texto en la parte superior. Ambos siguen el mismo atributo de gravedad.

Android sugerencia es sólo para algo así como una etiqueta donde el usuario tiene que empezar a introducir los caracteres.

No creo que esto sea posible "fuera de la caja", pero puede hacerlo de forma programática:

 yourEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0){ // position the text type in the left top corner yourEditText.setGravity(Gravity.LEFT | Gravity.TOP); }else{ // no text entered. Center the hint text. yourEditText.setGravity(Gravity.CENTER); } } } 

Yo estaba tratando de hacer el escenario opuesto – para que la sugerencia aparezca a la izquierda, y el texto escrito para aparecer en el medio, y encontré parte de la solución que necesitaba aquí, pero por el bien de alguien que está tratando de Hacer esto, pensé que publicaría mi solución completa, adaptado al escenario anterior :).

Así que como estaba tratando de averiguar esto, encontré que había dos desafíos: 1) Para que la sugerencia aparezca centrada, mientras que cualquier texto que el usuario escriba está alineado a la izquierda. 2) Para que el cursor aparezca inmediatamente donde aparecería el texto del usuario, en lugar de dónde comienza la pista. También quería que la pista permaneciera hasta que el usuario comenzara a escribir, y reaparecer cuando el usuario borrara lo que habían escrito.

Mi solución implicó dos cuadros de EditText acodados encima de uno a, con el rectángulo superior que contiene la indirecta, y el más bajo que contiene el texto. Como tal:

 <!-- This EditText box is where the user writes their text. It is aligned left, doesn't have a hint in it, and is the desired width of the box !--> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textShortMessage" android:fontFamily="sans-serif-medium" android:background="@color/white" android:layout_marginTop="5dp" android:id="@+id/event_heading" android:hint="" android:layout_below="@id/page_title" /> <!-- This second EditText box only contains the hint text. It is centered, is only the width of the hint text, and for my purposes, the text was italic !--> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textShortMessage" android:fontFamily="sans-serif-medium" android:background="@color/white" android:layout_marginTop="5dp" android:layout_below="@id/page_title" android:id="@+id/event_headingHint" android:hint="Heading" android:gravity="center" android:textStyle="italic" /> 

La caja que contenía la pista era la segunda, de modo que apareció por encima de la otra. Yo estaba usando esto dentro de un fragmento, así que luego anuló onCreateView en el fragmento, sacó los dos cuadros EditText, y los envió a un método que escribí para agregar los oyentes necesarios de la siguiente manera:

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_create_event, container, false); EditText heading = (EditText) view.findViewById(R.id.event_heading); EditText headingHint = (EditText) view.findViewById(R.id.event_headingHint); addFormatTidier(heading, headingHint); return view; } 

De lo contrario, si intenta hacerlo dentro de una actividad en lugar de un fragmento, podría utilizar el mismo código dentro del método onCreate, justo después del comando setContentView así:

 @Override protected void onCreate(Bundle savedInstanceState) { ... setContentView(R.layout.activity_add_event); EditText heading = (EditText) findViewById(R.id.event_heading); EditText headingHint = (EditText) findViewById(R.id.event_headingHint); addFormatTidier(heading, headingHint); ... } 

Entonces finalmente para mi método de "addFormatTidier", agregué un oyente a cada caja de EditText: Primero até un oyente onFocusChange a la "indirecta" EditText, para mover el foco sobre al otro EditText si el usuario chascó en la indirecta. A continuación, adjunto un addTextChangedListener a mi otro EditText, con el fin de eliminar la pista una vez que el usuario comenzó a escribir, y para restaurarlo si el usuario eliminado todo lo que había escrito, de la siguiente manera:

 private void addFormatTidier(final EditText text, final EditText hint) { // save the hint so I can restore it later final CharSequence hintText = hint.getHint(); // Add a listener to shift focus away from the hint text to the other EditText when the hint is clicked. hint.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { text.requestFocus(); } } }); // Add a listener to remove the hint text when the user starts typing, and to restore it when the user clears what they have typed. text.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { hint.setHint(""); } else { hint.setHint(hintText); } } }); } 

Para que la sugerencia desaparezca tan pronto como el usuario haga clic en el campo y vuelva a aparecer si hacen clic sin dejar ningún texto en el interior, se podría utilizar el siguiente método:

 private void addFormatTidier(final EditText text, final EditText hint) { // save the hint so I can restore it later final CharSequence hintText = hint.getHint(); // Add a listener to shift focus away from the hint text to the other EditText when the hint is clicked, and simultaneously clear the hint text. hint.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { text.requestFocus(); hint.setHint(""); } } }); // Add a listener to remove the hint text when the main EditText receives focus, and to restore it when the EditText loses focus without any text inside it. text.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { hint.setHint(""); } else { if(!(text.getText().length()>0)) { hint.setHint(hintText); } } } }); } 

Espero que esto sea útil para cualquier otra persona tratando de averiguar cómo resolver un problema similar: D. Fue userM1433372 en su comentario anterior que me puso en el camino correcto por donde empezar: D.

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.