Basic Android code - EditText's InputType - why was the bitwise operator used?

六眼飞鱼酱① 提交于 2019-12-23 06:13:41

问题


I'm working my way through a bunch of Android tutorials on YouTube, I expect they are a bit out of date by now. The bit I'm on currently has the following code:

tglButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        if (tglButton.isChecked()) {
            inputText.setInputType(InputType.TYPE_CLASS_TEXT | 
                                   InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {
            inputText.setInputType(InputType.TYPE_CLASS_TEXT);
        }
    }
});

The video glazes over why the bitwise operator is used here, and the top comment says that:

Each of the InputTypes are actually just ints. TYPE_CLASS_TEXT is 1, and TYPE_TEXT_VARIATION_PASSWORD is 128 (or 10000000).

Perform a bitwise OR on them:

00000001

10000000


10000001

which is 129.

Try entering input.setInputType(129); instead, you'll see it'll work. :)

Why? The aim of this part is to toggle the type of the EditText from text to password depending on the state of the ToggleButton. Why is it 129, and not 128, and why, for that matter is it even used.

I'm sure there's a better way to achieve this; but I am hoping to understand why it has been done this way.


回答1:


This type of construct is common in programming. These type of integers are sometimes referred to as binary flags. Flags can be combined and tested quickly with binary operations which computers can do very quickly. If an object (here an EditText) can perform differently depending on several settings, assigning those settings using binary flags can be efficient. An integer in Java is 32 bits, so 32 individual flags can be supported and many more values if flags are combined. Here the EditText is being told either to be a text field only (TYPE_CLASS_TEXT is binary 1, which is also integer 1) or to become a password field by flagging it with TYPE_TEXT_VARIATION_PASSWORD (binary 10000000 or integer 128). The binary OR on the values results in 10000001, integer 129. So 129 represents a password text field (i.e. it is flagged as text and password). If it was an OR on TYPE_CLASS_TEXT with TYPE_TEXT_VARIATION_EMAIL_ADDRESS (binary 100000, integer 32) the result would be 100001, integer 33, so 33 represents a text field flagged to check for an email address.



来源:https://stackoverflow.com/questions/9951326/basic-android-code-edittexts-inputtype-why-was-the-bitwise-operator-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!