如何强制editText框格式化缩进替换文本?

问题描述 投票:1回答:1

我的xml文件中有一个editTextBox被修改。最初,我缩进已经存在的文本但是当我用新文本替换时,我的缩进消失了。这是有道理的,因为我需要在我.setText(我的字符串)之前缩进新字符串。我很想知道,我们可以强制格式化一个editTextbox,它接受任何输入的字符串并将其转换为某种风格吗?

// 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.
java android textbox formatting
1个回答
1
投票

您可以使用TextWatcher来完成您要查找的内容。这是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);
                }
            }
        });
    }
}

请注意,您必须在更改可编辑之前删除TextWatcher,否则您将获得一个StackOverFlow来触发TextWatcher中的更改

© www.soinside.com 2019 - 2024. All rights reserved.