I'm trying to override getText() method from EditText (which extends TextView). I need to do some checks on who's calling my custom method and if all checks are passed then call the "original" EditText.getText().

The issue resides in the fact that my custom method gets called multiple times until an OOM error gets thrown at me, note that my custom method isn't yet called from nowhere.

This is the code: (the aforementioned checks are not in here, I've just pasted the orignal EditText.getText implementation as a replacement but the issue is still present)

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();

    }

}

This is my MainActivity:

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);

    }
}

I expect not to read multiple "Should be printed once called..." at Runtime, at this point I should expect not to see even one instance of it since the method hasn't been yet called.

1 Answers

0
Community On Best Solutions

EditText extends from TextView class and TextView class with call getText() method in its constructor. This happens whenever you create any instance of a custom widget that's a direct/indirect subclass of TextView, I guess this is the reason, your custom view's getText() gets invoked, even though it's nowhere invoked in your project code.

If you want to perform some checks and then invoke original getText() method, to get the value from it, then don't override the method in your custom class. Have a normal method in your custom class that has those checks and then calls the original method(to get the value) based on those checks, then you can return value from your normal method.