I have an editTextBox in my xml file that gets modified. Initially, I indent the text already present but when I replace with new text my indentation is gone. This makes sense because I need to indent the new string before I .setText(my string). I am curious to know, can we force format an editTextbox that takes any inputted string and converts it to a certain style?
// My orginal string. I already indent here, but once I change the string, I lose my indentation.
<string name="first_name">\tFirst Name</string>
// Whenever I am getting a new string. I need to tell it to format by tab again.
name.setText(String.format(" %s", user.firstName));
// I want to be able to force my edittext...
<EditText
android:id="@+id/enterText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="@+id/title_of_the_field"
android:layout_marginTop="27dp"
android:hint="@string/hint"
android:imeActionLabel="Done"
android:singleLine="false"
android:textAlignment="center"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
// To take any string that is put inside it to auto convert it into a desired style.
You could use a TextWatcher to accomplish what you're looking for. Here's a quick example in Java:
public class SomeActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...)
editText = findViewById(R.id.some_edit_text);
editText.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) {
if(TextUtils.isEmpty(s) || s.charAt(0) != ' '){
editText.removeTextChangedListener(this);
s.insert(0, " ");
editText.addTextChangedListener(this);
}
}
});
}
}
Note that you have to remove the TextWatcher before changing the Editable, otherwise you'll get a StackOverFlow from triggering a change within the TextWatcher