java - 如何修复 EditText 的 getText 方法的重写

标签 java android android-edittext

我正在尝试重写 EditText(扩展 TextView)中的 getText() 方法。 我需要对谁在调用我的自定义方法进行一些检查,如果所有检查都通过,则调用“原始”EditText.getText()。

问题在于,我的自定义方法被多次调用,直到向我抛出 OOM 错误,请注意,我的自定义方法尚未从任何地方调用。

这是代码:(上述检查不在这里,我刚刚粘贴了原始的 EditText.getText 实现作为替换,但问题仍然存在)

public class CustomEdit extends EditText {


    public CustomEdit(Context context) {
        this(context, null);
    }

    public CustomEdit(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomEdit(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public Editable getText() {

        System.out.println("Should be printed once called...");

        CharSequence text = super.getText();

        if (text == null) {
            return null;
        }
        if (text instanceof Editable) {
            return (Editable) super.getText();
        }
        super.setText(text, BufferType.EDITABLE);
        return (Editable) super.getText();

    }

}

这是我的主要 Activity :

public class MainActivity extends AppCompatActivity {

    CustomEdit s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        s = findViewById(R.id.newEditText);

    }
}

我希望在运行时不会读取多个“应该在调用一次后打印...”,此时我应该不会看到它的一个实例,因为该方法尚未被调用。

最佳答案

EditText 继承自 TextView 类和 TextView 类,并在其构造函数中调用 getText() 方法。每当您创建作为 TextView 的直接/间接子类的自定义小部件的任何实例时,都会发生这种情况,我想这就是调用您的自定义 View 的 getText() 的原因,即使它在您的项目代码中没有被调用。

如果您想执行一些检查,然后调用原始 getText() 方法,以从中获取值,则不要重写自定义类中的该方法。在您的自定义类中拥有一个具有这些检查的普通方法,然后根据这些检查调用原始方法(以获取值),然后您可以从普通方法返回值。

关于java - 如何修复 EditText 的 getText 方法的重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099969/

相关文章:

java - RecyclerView Adapter 性能方法

android - filter 方法在更改键盘语言时被调用两次 android edittext

java - 在lucene中搜索时需要创建term shingles

java.io.StreamCorruptedException : Is there a list of Invalid code types with description?

Android 数据存储 : how to create it with a dynamic filename?

android - 如何在android EditText中禁用自动完成右括号

android - 如何在android中限制EditText只获取文本不获取数字

java - Server Tomcat v9.0 Server at localhost failed to start 是eclipse中的消息

java - 尝试在 cmd 中运行我的项目时出错

android - 在 init.rc 中启用 logcat