开发者

Android: Cyclic event chain, how to avoid it?

开发者 https://www.devze.com 2023-03-18 18:21 出处:网络
The problem Similar to the question regarding Swing ( The Elegant way t开发者_JS百科o handle Cyclic Event in Java? ) I\'m looking for a elegant way to avoid a cyclic event chain where two widget vie

The problem

Similar to the question regarding Swing ( The Elegant way t开发者_JS百科o handle Cyclic Event in Java? ) I'm looking for a elegant way to avoid a cyclic event chain where two widget views depend on each other.

More specifically I have two EditText's, one of them represents a weight in kg, the other the weight in lb. The user should be able to enter text in either and have the other updated as he/she types.

What I've tried

The only way to act on a change in the controller that I've found is to register a TextWatcher on each EditText view. But how do I elegantly avoid the circular event chain that occurs if I modify the other EditText in the callback.

I tried sub-classing EditText and bind them together without using TextWatcher by overloading setText and have that method modify the value and call setText of the other controller. But that doesn't work not calling setText, which seems to be the case when user enters text from UI and not programmatically.

Any ideas would be helpful, thanks.


I ended up adding and removing TextWatcher's when the controller is focused and unfocused. This has the drawback that the same mirroring code is not used when setting a controller's text programmatically (unless I programmatically set the focus as well, which is not a very nice solution, IMO).

It works fine, but I still think there's a cleaner solution out there.

0

精彩评论

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

关注公众号