Android: showing text in EditText from start

2019-05-16 06:11发布

问题:

I have an EditText view in my xml file with a certain width. I have forced it to 1 line, so that if the entered text is longer than the width of my edit text, the text does not wrap around by using:

android:singleLine="true"

However, after entering a long text (longer than the width of edit text) it shows the last part of the text. I would like after user finishes entering the text, the text to be shown from the start. For example assume I have an edit text with a width that only accepts 4 characters. So if I enter "ABCDEFG" in the EditText box I see "DEFG" but I want to see "ABCD". How can this be done.

here is my EditText in XML:

<EditText
    android:id="@+id/fileNameBox"
    android:layout_width = "0dp"
    android:layout_height="40dp"
    android:gravity="left"
    android:ellipsize="start"
    android:singleLine="true"
    android:textSize="14sp" 
    android:layout_weight="0.5" 
    android:layout_marginBottom="1dip"/>

Thanks for the help.

TJ

回答1:

Setting a focus change listener to EditText should fulfill your need.

mEdittext.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
    public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus == false) {  // lost focus
       mEdittext.setSelection(0,0);
    }
}
});


回答2:

Have you tried android:ellipsize?



回答3:

Have a look at the android:ellipsize property and set it to 'end'.