Привет, у меня есть текст редактирования с подсказкой, я сделал подсказку как среднюю, используя android:gravity:"center"
. когда я начинаю вводить текст из edittext, ввод начинается с середины, как сделать начало ввода с левого горизонта, пока все же намек центрируется.
Ответ 3
Я пытался сделать противоположный сценарий - чтобы подсказка появилась слева, и напечатанный текст появлялся посередине, и я нашел часть решения, которое мне нужно здесь, но ради кого-либо еще, кто пытается это сделать, я думал, что опубликую свое полное решение, адаптированное к описанному выше сценарию:).
Так как я пытался понять это, я обнаружил, что есть две проблемы:
1) Чтобы подсказка отображалась по центру, в то время как любой текст, который пользователь вводит, выравнивается влево.
2) Для того, чтобы курсор сразу отображался там, где будет отображаться текст пользователя, а не там, где начинается подсказка.
Я также хотел, чтобы подсказка оставалась до тех пор, пока пользователь не начал вводить текст и снова появлялся, когда пользователь удалял то, что они набрали.
В моем решении участвовали два блока EditText, расположенных сверху друг друга, с верхним полем, содержащим подсказку, и нижним, содержащим текст. как это:
<!-- 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"
/>
Ящик, содержащий подсказку, был вторым, так что он появился над другим.
Я использовал это внутри фрагмента, чтобы затем перекрыть onCreateView в фрагменте, вытащил два блока EditText и отправил их методу, который я написал для добавления необходимых слушателей, следующим образом:
@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;
}
В противном случае, если вы попытаетесь сделать это внутри Activity, а не с помощью фрагмента, вы можете использовать тот же код внутри метода onCreate сразу после команды setContentView:
@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);
...
}
Затем, наконец, для моего метода addFormatTidier, я добавил слушателя в каждый блок EditText: сначала я подключил прослушиватель onFocusChange к текстовому редактору 'hint' EditText, чтобы переместить фокус на другой EditText, если пользователь нажал на подсказку, Затем я привязал addTextChangedListener к другому редактору EditText, чтобы удалить подсказку после того, как пользователь начал вводить текст, и восстановить его, если пользователь удалил все, что они набрали, следующим образом:
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);
}
}
});
}
Чтобы подсказка исчезла, как только пользователь нажмет на поле и снова появится, если они щелкнут, не выходя из текста внутри, вместо этого можно использовать следующий метод:
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);
}
}
}
});
}
Надеюсь, это полезно для всех, кто пытается выяснить, как решить подобную проблему: D. Это был userM1433372 в его комментарии выше, который поставил меня на правильном пути для того, где начать: D.