简体   繁体   中英

How to setText in selected textView

Needed some help here. In my map test app I have 2 Autocomplete textViews. First textView gets the address of marker on load as well as chages the address if map is dragged.

But I am struggling for second textView where I need the same feature depending which textView is active.

I tried it like:

private AutoCompleteTextView mFromAddress;
private AutoCompleteTextView mToAddress;

mFromAddress = (AutoCompleteTextView) findViewById(R.id.fromAddress);
mToAddress = (AutoCompleteTextView) findViewById(R.id.toAddress);

// Decoder Coding.. str prints address
if (mFromAddress.isSelected()) {
    mFromAddress.setText(str);
} else if (mToAddress.isSelected()) {
    mToAddress.setText(str);
}

But no expected results. Even the first textView stops working.

I am new to java and Android Studio. I am looking for some suggestions here.

Try hasFocus() function

if (mFromAddress.hasFocus()) {
    mFromAddress.setText(str);
} else if (mToAddress.hasFocus()) {
    mToAddress.setText(str);
}

Another way is that define another TextView in code and set it as active TextView when focus change in OnFocusChangeListener

AutoCompleteTextView activeET;
activeET = mFromAddress;  // set mFromAddress as active text in start

mFromAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if(hasFocus)
            activeET = mFromAddress;
    }
});

mToAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if(hasFocus)
            activeET = mToAddress;
    }
});

Now you just need to set text to activeET

activeET.setText(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM