Please explain to the beginner the meaning of the line (2) of this code. The more detailed the better, thank you in advance :)

TextView display = (TextView) findViewById(R.id.display); display.setKeyListener(DigitsKeyListener.getInstance(true,true)); 

    2 answers 2

    We hang on the TextView listener. But why on TextView this listener ? You need it to EditText . DigitsKeyListener , according to official documentation:

    For digital input only

    As for all implementations of KeyListener, this class deals only with the hardware keyboard. The soft keyboard will not necessarily call methods in this class.

    getInstance - get the object of this class.

    Look at him:

     private static final int SIGN = 1; private static final int DECIMAL = 2; public static DigitsKeyListener getInstance(boolean sign, boolean decimal) { int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0); //1 if (sInstance[kind] != null) return sInstance[kind]; sInstance[kind] = new DigitsKeyListener(sign, decimal); return sInstance[kind]; } 

    Line with comment 1 - we get the number, in the case (true, true) it is 3. We check if it is not null and if not, return it, if it is equal, then create a new object and return it. In short all.

      DigitsKeyListener does not allow typing something other than a number in the text field. The first true allows negative numbers (the first character may be a '-'). The second true allows the number to be decimal (somewhere among the digits there may be one '.'). Works reliably only with the hardware keyboard.