【问题标题】:How to force an editTextbox to format any replaced text by indentation?如何强制编辑文本框通过缩进格式化和替换文本?
【发布时间】:2018-03-01 15:52:49
【问题描述】:

我的 xml 文件中有一个 editTextBox 被修改。最初,我缩进了已经存在的文本,但是当我用新文本替换时,我的缩进消失了。这是有道理的,因为我需要在 .setText(my string) 之前缩进新字符串。我很想知道,我们可以强制格式化一个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】:

您可以使用 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);
                }
            }
        });
    }
}

请注意,您必须在更改 Editable 之前删除 TextWatcher,否则您将通过触发 TextWatcher 中的更改而获得 StackOverFlow

【讨论】:

  • 我以前从未使用过 koltin。我知道,如果我在启动项目时选择了 koltin 支持,它就会启用。我现在有办法使用它吗?
  • 为 Java 编辑,还请注意,如果您想检查制表符,可能需要使用 '\t' 字符而不是空格字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 2023-03-03
相关资源
最近更新 更多