开发者

Populate EditText widget text from another EditText widget text

I am trying to populate the text of a second EditText widget with the text from the first EditText widget only when the second EditText widget receives focus, the second widget is not empty, and the first widget is not empty.

I have the following OnFocusChangeListener handler code.

        public void onFocusChange(View v, boolean hasFocus) {

        EditText stxt = (EditText) findViewById(R.id.numberone);
        EditText etxt = (EditText) findViewById(R.id.numbertwo);


        if (hasFocus && stxt.getText().toString().trim() != "" && etxt.getText ().toString().trim() == "")
        {
            etxt.setText(stxt.getText().toString().trim());
        }
    }

When I run it and click into the second widget it does not populate. When I remove the third constraint ('etxt.getText ().toString().trim() == ""')) it works. so getText() on the second EditText widget is returning something even though the second widget has no initial value other the开发者_JAVA百科n the text that is displayed via the hint attribute.

How can I accomplish this.

Thanks


You should be doing an object comparison using String.equals(), not just x == "".

I would rewrite this using Android's handy TextUtils class:

String one = stxt.getText().toString();
String two = etxt.getText().toString();

if (hasFocus && TextUtils.getTrimmedLength(one) != 0 
      && TextUtils.getTrimmedLength(two) == 0) {
    etxt.setText(one);
}


Never compare strings in Java with == or !=. Use equals(). Try that and see if you get better results.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜