How can we override getText method in EditText?

2019-07-27 23:24发布

问题:

I have override this method in MyEditText class:

@Override
public Editable getText() {
    Editable s = (Editable) super.getText();
    s.toString().replace("$", "").trim();
    return s;
}

MainActivity class is:

public class MainActivity extends Activity implements OnClickListener {
MyEditText myEditText;
Button btn;
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.try_layout);

    myEditText = new MyEditText(this);

    btn = (Button) findViewById(R.id.btn);
    tv = (TextView) findViewById(R.id.tv);
    btn.setOnClickListener(this);

}
@Override
public void onClick(View v) {

    tv.setText(myEditText.getText().toString());

   }

}

When i entered some values in edittext then click on btn nothing text is get from edittext why.

回答1:

Why you do not assign back to 's' before return?

s = s.toString().replace("$", "").trim();


回答2:

Editable s = (Editable) super.getText();
s.toString().replace("$", "").trim();
return s;

I am afraid that you got some issuse here, because the replace return a new string, you can try return (s.toString().replace("$", "").trim(); instead of



回答3:

Change this

   @Override
    public Editable getText() {
        Editable s = (Editable) super.getText();
        s.toString().replace("$", "").trim();
        return s;
    }

to

 @Override
    public Editable getText() {
        Editable s = (Editable) super.getText();
        return new SpannableStringBuilder(s.toString().replace("$", "").trim());
    }