How can we override getText method in EditText?

2019-07-27 22:46发布

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.

3条回答
欢心
2楼-- · 2019-07-27 23:19

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());
    }
查看更多
男人必须洒脱
3楼-- · 2019-07-27 23:26
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

查看更多
ら.Afraid
4楼-- · 2019-07-27 23:33

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

s = s.toString().replace("$", "").trim();
查看更多
登录 后发表回答