Java Code Examples for android.text.InputFilter#LengthFilter

The following examples show how to use android.text.InputFilter#LengthFilter . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FormattedEditText.java    From FormatEditText with MIT License 6 votes vote down vote up
@Override
@CallSuper
public void setFilters(InputFilter[] filters) {
    if (filters == null) {
        throw new IllegalArgumentException("filters can not be null");
    }
    boolean havingFilter = false;
    for (int i = 0; i < filters.length; i++) {
        if (filters[i] instanceof InputFilter.LengthFilter) {
            mLengthFilterDelegate = new LengthFilterDelegate(filters[i]);
            filters[i] = mLengthFilterDelegate;
        } else if (filters[i] instanceof PlaceholderFilter) {
            havingFilter = true;
        }
    }
    if (!havingFilter) {
        InputFilter[] replaceFilters = new InputFilter[filters.length + 1];
        replaceFilters[0] = new PlaceholderFilter();
        System.arraycopy(filters, 0, replaceFilters, 1, filters.length);
        super.setFilters(replaceFilters);
        return;
    }
    super.setFilters(filters);
}
 
Example 2
Source File: TextInputProxyEditTextbox.java    From ForgePE with GNU Affero General Public License v3.0 6 votes vote down vote up
public TextInputProxyEditTextbox(Context context, int allowedLength, boolean limitInput) {
    super(context);
    this.allowedLength = allowedLength;
    this.limitInput = limitInput;

    if (limitInput) {
        InputFilter[] fillters = new InputFilter[2];
        fillters[0] = new InputFilter.LengthFilter(this.allowedLength);
        fillters[1] = new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals("") || source.toString().matches("^[a-zA-Z0-9_ -^~\'.,;!#&()=`{}]*"))
                    return source;
                return "";
            }
        };
        setFilters(fillters);
    } else
        setFilters(new InputFilter[]{new InputFilter.LengthFilter(this.allowedLength)});
}
 
Example 3
Source File: EditTextUtil.java    From AndroidBasicProject with MIT License 6 votes vote down vote up
/**
 * 限制内容长度
 */
public static void lengthFilter(final EditText editText, final int length) {
    InputFilter[] filters = new InputFilter[1];

    filters[0] = new InputFilter.LengthFilter(length) {
        public CharSequence filter(@NonNull CharSequence source, int start, int end,
            @NonNull Spanned dest, int dstart, int dend) {
            if (dest.toString().length() >= length) {
                return "";
            }
            return source;
        }
    };
    // Sets the list of input filters that will be used if the buffer is Editable. Has no effect otherwise.
    editText.setFilters(filters);
}
 
Example 4
Source File: PasscodeActivity.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private void updateDropDownTextView() {
    if (dropDown != null) {
        if (currentPasswordType == 0) {
            dropDown.setText(LocaleController.getString("PasscodePIN", R.string.PasscodePIN));
        } else if (currentPasswordType == 1) {
            dropDown.setText(LocaleController.getString("PasscodePassword", R.string.PasscodePassword));
        }
    }
    if (type == 1 && currentPasswordType == 0 || type == 2 && SharedConfig.passcodeType == 0) {
        InputFilter[] filterArray = new InputFilter[1];
        filterArray[0] = new InputFilter.LengthFilter(4);
        passwordEditText.setFilters(filterArray);
        passwordEditText.setInputType(InputType.TYPE_CLASS_PHONE);
        passwordEditText.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
    } else if (type == 1 && currentPasswordType == 1 || type == 2 && SharedConfig.passcodeType == 1) {
        passwordEditText.setFilters(new InputFilter[0]);
        passwordEditText.setKeyListener(null);
        passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }
    passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
 
Example 5
Source File: PasscodeActivity.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private void updateDropDownTextView() {
    if (dropDown != null) {
        if (currentPasswordType == 0) {
            dropDown.setText(LocaleController.getString("PasscodePIN", R.string.PasscodePIN));
        } else if (currentPasswordType == 1) {
            dropDown.setText(LocaleController.getString("PasscodePassword", R.string.PasscodePassword));
        }
    }
    if (type == 1 && currentPasswordType == 0 || type == 2 && SharedConfig.passcodeType == 0) {
        InputFilter[] filterArray = new InputFilter[1];
        filterArray[0] = new InputFilter.LengthFilter(4);
        passwordEditText.setFilters(filterArray);
        passwordEditText.setInputType(InputType.TYPE_CLASS_PHONE);
        passwordEditText.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
    } else if (type == 1 && currentPasswordType == 1 || type == 2 && SharedConfig.passcodeType == 1) {
        passwordEditText.setFilters(new InputFilter[0]);
        passwordEditText.setKeyListener(null);
        passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }
    passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
 
Example 6
Source File: EditTextUtil.java    From zone-sdk with MIT License 6 votes vote down vote up
/**
 * 限制中文字符的长度
 */
public static void lengthChineseFilter(final EditText editText, final int length) {
    InputFilter[] filters = new InputFilter[1];

    filters[0] = new InputFilter.LengthFilter(length) {
        public CharSequence filter(@NonNull CharSequence source, int start, int end, @NonNull Spanned dest, int dstart, int dend) {
            // 可以检查中文字符
            boolean isChinese = CharacterCheck.checkNameChese(source.toString());
            if (!isChinese || dest.toString().length() >= length) {
                return "";
            }
            return source;
        }
    };
    // Sets the list of input filters that will be used if the buffer is Editable. Has no effect otherwise.
    editText.setFilters(filters);
}
 
Example 7
Source File: PhotoViewerCaptionEnterView.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
public void setFieldText(CharSequence text) {
    if (messageEditText == null) {
        return;
    }
    messageEditText.setText(text);
    messageEditText.setSelection(messageEditText.getText().length());
    if (delegate != null) {
        delegate.onTextChanged(messageEditText.getText());
    }
    int old = captionMaxLength;
    captionMaxLength = MessagesController.getInstance(UserConfig.selectedAccount).maxCaptionLength;
    if (old != captionMaxLength) {
        InputFilter[] inputFilters = new InputFilter[1];
        inputFilters[0] = new InputFilter.LengthFilter(captionMaxLength);
        messageEditText.setFilters(inputFilters);
    }
}
 
Example 8
Source File: RichEditText.java    From GSYRickText with MIT License 5 votes vote down vote up
private void init(Context context, AttributeSet attrs) {

        if (isInEditMode())
            return;

        if (attrs != null) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RichEditText);
            int textLength = array.getInteger(R.styleable.RichEditText_richMaxLength, 9999);
            float iconSize = (int) array.getDimension(R.styleable.RichEditText_richIconSize, 0);
            String colorAtUser = array.getString(R.styleable.RichEditText_richEditColorAtUser);
            String colorTopic = array.getString(R.styleable.RichEditText_richEditColorTopic);
            richMaxLength = textLength;
            InputFilter[] filters = {new InputFilter.LengthFilter(richMaxLength)};
            setFilters(filters);
            if (iconSize == 0) {
                richIconSize = dip2px(context, 20);
            }
            if (!TextUtils.isEmpty(colorAtUser)) {
                this.colorAtUser = colorAtUser;
            }
            if (!TextUtils.isEmpty(colorTopic)) {
                this.colorTopic = colorTopic;
            }
            array.recycle();
        }

        resolveAtPersonEditText();
    }
 
Example 9
Source File: MascaraNumericaTextWatcher.java    From canarinho with Apache License 2.0 5 votes vote down vote up
private MascaraNumericaTextWatcher(Builder builder) {
    this.mascara = builder.mascara.toCharArray();
    this.validador = builder.validador;

    final int length = mascara.length;
    this.filtroNumerico = new InputFilter[]{new InputFilter.LengthFilter(length)};

    setEventoDeValidacao(builder.eventoDeValidacao);
}
 
Example 10
Source File: TextInputSpec.java    From litho with Apache License 2.0 5 votes vote down vote up
/** LengthFilter and AllCaps do not implement isEqual. Correct for the deficiency. */
private static boolean equalInputFilters(List<InputFilter> a, List<InputFilter> b) {
  if (a == null && b == null) {
    return true;
  }
  if (a == null || b == null) {
    return false;
  }
  if (a.size() != b.size()) {
    return false;
  }
  for (int i = 0; i < a.size(); i++) {
    InputFilter fa = a.get(i);
    InputFilter fb = b.get(i);
    if (fa instanceof InputFilter.AllCaps && fb instanceof InputFilter.AllCaps) {
      continue; // equal, AllCaps has no configuration
    }
    if (SDK_INT >= LOLLIPOP) { // getMax added in lollipop
      if (fa instanceof InputFilter.LengthFilter && fb instanceof InputFilter.LengthFilter) {
        if (((InputFilter.LengthFilter) fa).getMax()
            != ((InputFilter.LengthFilter) fb).getMax()) {
          return false;
        }
        continue; // equal, same max
      }
    }
    // Best we can do in this case is call equals().
    if (!equals(fa, fb)) {
      return false;
    }
  }
  return true;
}
 
Example 11
Source File: PasscodeActivity.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void updateDropDownTextView()
{
    if (dropDown != null)
    {
        if (currentPasswordType == 0)
        {
            dropDown.setText(LocaleController.getString("PasscodePIN", R.string.PasscodePIN));
        }
        else if (currentPasswordType == 1)
        {
            dropDown.setText(LocaleController.getString("PasscodePassword", R.string.PasscodePassword));
        }
    }
    if (type == 1 && currentPasswordType == 0 || type == 2 && SharedConfig.passcodeType == 0)
    {
        InputFilter[] filterArray = new InputFilter[1];
        filterArray[0] = new InputFilter.LengthFilter(4);
        passwordEditText.setFilters(filterArray);
        passwordEditText.setInputType(InputType.TYPE_CLASS_PHONE);
        passwordEditText.setKeyListener(DigitsKeyListener.getInstance("1234567890"));
    }
    else if (type == 1 && currentPasswordType == 1 || type == 2 && SharedConfig.passcodeType == 1)
    {
        passwordEditText.setFilters(new InputFilter[0]);
        passwordEditText.setKeyListener(null);
        passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }
    passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
 
Example 12
Source File: CardCVVFragment.java    From CreditCardView with Apache License 2.0 5 votes vote down vote up
public void setMaxCVV(int maxCVVLength) {
    if (mCardCVVView != null && (mCardCVVView.getText().toString().length() > maxCVVLength)) {
        mCardCVVView.setText(mCardCVVView.getText().toString().substring(0, maxCVVLength));
    }

    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(maxCVVLength);
    mCardCVVView.setFilters(FilterArray);
    mMaxCVV = maxCVVLength;
    String hintCVV = "";
    for (int i = 0; i < maxCVVLength; i++) {
        hintCVV += "X";
    }
    mCardCVVView.setHint(hintCVV);
}
 
Example 13
Source File: CancelAccountDeletionActivity.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void setParams(Bundle params, boolean restore) {
    if (params == null) {
        return;
    }
    codeField.setText("");
    waitingForEvent = true;
    if (currentType == 2) {
        AndroidUtilities.setWaitingForSms(true);
        NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didReceiveSmsCode);
    } else if (currentType == 3) {
        AndroidUtilities.setWaitingForCall(true);
        NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didReceiveCall);
    }

    currentParams = params;
    phone = params.getString("phone");
    phoneHash = params.getString("phoneHash");
    timeout = time = params.getInt("timeout");
    openTime = (int) (System.currentTimeMillis() / 1000);
    nextType = params.getInt("nextType");
    pattern = params.getString("pattern");
    length = params.getInt("length");

    if (length != 0) {
        InputFilter[] inputFilters = new InputFilter[1];
        inputFilters[0] = new InputFilter.LengthFilter(length);
        codeField.setFilters(inputFilters);
    } else {
        codeField.setFilters(new InputFilter[0]);
    }
    if (progressView != null) {
        progressView.setVisibility(nextType != 0 ? VISIBLE : GONE);
    }

    if (phone == null) {
        return;
    }

    String number = PhoneFormat.getInstance().format(phone);
    CharSequence str;
    /*if (currentType == 1) {
        str = AndroidUtilities.replaceTags(LocaleController.getString("SentAppCode", R.string.SentAppCode));
    } else if (currentType == 2) {*/
    str = AndroidUtilities.replaceTags(LocaleController.formatString("CancelAccountResetInfo", R.string.CancelAccountResetInfo, PhoneFormat.getInstance().format("+" + number)));
    /*} else if (currentType == 3) {
        str = AndroidUtilities.replaceTags(LocaleController.formatString("SentCallCode", R.string.SentCallCode, number));
    } else if (currentType == 4) {
        str = AndroidUtilities.replaceTags(LocaleController.formatString("SentCallOnly", R.string.SentCallOnly, number));
    }*/
    confirmTextView.setText(str);

    if (currentType != 3) {
        AndroidUtilities.showKeyboard(codeField);
        codeField.requestFocus();
    } else {
        AndroidUtilities.hideKeyboard(codeField);
    }

    destroyTimer();
    destroyCodeTimer();

    lastCurrentTime = System.currentTimeMillis();
    if (currentType == 1) {
        problemText.setVisibility(VISIBLE);
        timeText.setVisibility(GONE);
    } else if (currentType == 3 && (nextType == 4 || nextType == 2)) {
        problemText.setVisibility(GONE);
        timeText.setVisibility(VISIBLE);
        if (nextType == 4) {
            timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 1, 0));
        } else if (nextType == 2) {
            timeText.setText(LocaleController.formatString("SmsText", R.string.SmsText, 1, 0));
        }
        createTimer();
    } else if (currentType == 2 && (nextType == 4 || nextType == 3)) {
        timeText.setVisibility(VISIBLE);
        timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 2, 0));
        problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
        createTimer();
    } else {
        timeText.setVisibility(GONE);
        problemText.setVisibility(GONE);
        createCodeTimer();
    }
}
 
Example 14
Source File: AbstractPasscodeKeyboardActivity.java    From UltimateAndroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.passlock_passcode_keyboard);
    
    topMessage = (TextView) findViewById(R.id.top_message);
    
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String message = extras.getString("message");
        if (message != null) {
            topMessage.setText(message);
        }
    }
    
    filters = new InputFilter[2];
    filters[0]= new InputFilter.LengthFilter(1);
    filters[1] = onlyNumber;
    
    //Setup the pin fields row
    pinCodeField1 = (EditText) findViewById(R.id.pincode_1);
    setupPinItem(pinCodeField1);
    
    pinCodeField2 = (EditText) findViewById(R.id.pincode_2);
    setupPinItem(pinCodeField2);
    
    pinCodeField3 = (EditText) findViewById(R.id.pincode_3);
    setupPinItem(pinCodeField3);
    
    pinCodeField4 = (EditText) findViewById(R.id.pincode_4);
    setupPinItem(pinCodeField4);
    
    //setup the keyboard
    ((Button) findViewById(R.id.button0)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button1)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button2)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button3)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button4)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button5)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button6)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button7)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button8)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button9)).setOnClickListener(defaultButtonListener);
    ((Button) findViewById(R.id.button_erase)).setOnClickListener(
            new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if( pinCodeField1.isFocused() ) {

                    }
                    else if( pinCodeField2.isFocused() ) {
                        pinCodeField1.requestFocus();
                        pinCodeField1.setText("");
                    }
                    else if( pinCodeField3.isFocused() ) {
                        pinCodeField2.requestFocus();
                        pinCodeField2.setText("");
                    }
                    else if( pinCodeField4.isFocused() ) {
                        pinCodeField3.requestFocus();
                        pinCodeField3.setText("");
                    }
                }
            });
}
 
Example 15
Source File: CustomInputDialog.java    From GSYVideoPlayer with Apache License 2.0 4 votes vote down vote up
public void init() {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.layout_custom_dialog, null);
    setContentView(view);
    txtTitle = (TextView) view.findViewById(R.id.dialog_input_title);
    editMessage = (EditText) view.findViewById(R.id.dialog_input_dialog_edit);
    btnPostive = (TextView) view.findViewById(R.id.dialog_input_dialog_postive);
    btnNegative = (TextView) view.findViewById(R.id.dialog_input_dialog_negative);
    cacheCheck = (CheckBox) view.findViewById(R.id.dialog_input_check);

    cacheCheck.setChecked(cache);

    if (postiveButtonVisiable) {
        btnPostive.setVisibility(View.VISIBLE);
    } else {
        btnPostive.setVisibility(View.GONE);
    }
    if (negativeButtonVisiable) {
        btnNegative.setVisibility(View.VISIBLE);
    } else {
        btnNegative.setVisibility(View.GONE);
    }

    if (TextUtils.isEmpty(title)) {
        txtTitle.setVisibility(View.GONE);
    } else {
        txtTitle.setVisibility(View.VISIBLE);
        txtTitle.setText(title);
    }
    editMessage.setText(input);
    if (input != null) {
        editMessage.setSelection(input.length());
    }
    if (!TextUtils.isEmpty(hintInput)) {
        editMessage.setHint(hintInput);
    }
    btnPostive.setText(postiveText);
    btnNegative.setText(negativeText);
    btnPostive.setOnClickListener(new OnButtonClickListener());
    btnNegative.setOnClickListener(new OnButtonClickListener());
    InputFilter[] filters = {new InputFilter.LengthFilter(maxLength)};
    editMessage.setFilters(filters);
    Window dialogWindow = getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
    lp.width = (int) (d.widthPixels * 0.8); // 宽度设置为屏幕的0.8
    dialogWindow.setAttributes(lp);
}
 
Example 16
Source File: UserReviseActivity.java    From Android-Application-ZJB with Apache License 2.0 4 votes vote down vote up
private void setMaxLength(int maxLength) {
    InputFilter[] fArray = new InputFilter[1];
    fArray[0] = new InputFilter.LengthFilter(maxLength);
    mEditText.setFilters(fArray);
}
 
Example 17
Source File: SecurityCodeActivity.java    From px-android with MIT License 4 votes vote down vote up
private void setInputMaxLength(final MPEditText text, final int maxLength) {
    final InputFilter[] fArray = new InputFilter[1];
    fArray[0] = new InputFilter.LengthFilter(maxLength);
    text.setFilters(fArray);
}
 
Example 18
Source File: CancelAccountDeletionActivity.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void setParams(Bundle params, boolean restore) {
    if (params == null) {
        return;
    }
    codeField.setText("");
    waitingForEvent = true;
    if (currentType == 2) {
        AndroidUtilities.setWaitingForSms(true);
        NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didReceiveSmsCode);
    } else if (currentType == 3) {
        AndroidUtilities.setWaitingForCall(true);
        NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didReceiveCall);
    }

    currentParams = params;
    phone = params.getString("phone");
    phoneHash = params.getString("phoneHash");
    timeout = time = params.getInt("timeout");
    openTime = (int) (System.currentTimeMillis() / 1000);
    nextType = params.getInt("nextType");
    pattern = params.getString("pattern");
    length = params.getInt("length");

    if (length != 0) {
        InputFilter[] inputFilters = new InputFilter[1];
        inputFilters[0] = new InputFilter.LengthFilter(length);
        codeField.setFilters(inputFilters);
    } else {
        codeField.setFilters(new InputFilter[0]);
    }
    if (progressView != null) {
        progressView.setVisibility(nextType != 0 ? VISIBLE : GONE);
    }

    if (phone == null) {
        return;
    }

    String number = PhoneFormat.getInstance().format(phone);
    CharSequence str;
    /*if (currentType == 1) {
        str = AndroidUtilities.replaceTags(LocaleController.getString("SentAppCode", R.string.SentAppCode));
    } else if (currentType == 2) {*/
    str = AndroidUtilities.replaceTags(LocaleController.formatString("CancelAccountResetInfo", R.string.CancelAccountResetInfo, PhoneFormat.getInstance().format("+" + number)));
    /*} else if (currentType == 3) {
        str = AndroidUtilities.replaceTags(LocaleController.formatString("SentCallCode", R.string.SentCallCode, number));
    } else if (currentType == 4) {
        str = AndroidUtilities.replaceTags(LocaleController.formatString("SentCallOnly", R.string.SentCallOnly, number));
    }*/
    confirmTextView.setText(str);

    if (currentType != 3) {
        AndroidUtilities.showKeyboard(codeField);
        codeField.requestFocus();
    } else {
        AndroidUtilities.hideKeyboard(codeField);
    }

    destroyTimer();
    destroyCodeTimer();

    lastCurrentTime = System.currentTimeMillis();
    if (currentType == 1) {
        problemText.setVisibility(VISIBLE);
        timeText.setVisibility(GONE);
    } else if (currentType == 3 && (nextType == 4 || nextType == 2)) {
        problemText.setVisibility(GONE);
        timeText.setVisibility(VISIBLE);
        if (nextType == 4) {
            timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 1, 0));
        } else if (nextType == 2) {
            timeText.setText(LocaleController.formatString("SmsText", R.string.SmsText, 1, 0));
        }
        createTimer();
    } else if (currentType == 2 && (nextType == 4 || nextType == 3)) {
        timeText.setVisibility(VISIBLE);
        timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 2, 0));
        problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
        createTimer();
    } else {
        timeText.setVisibility(GONE);
        problemText.setVisibility(GONE);
        createCodeTimer();
    }
}
 
Example 19
Source File: TextQuestionBody.java    From ResearchStack with Apache License 2.0 4 votes vote down vote up
@Override
public View getBodyView(int viewType, LayoutInflater inflater, ViewGroup parent) {
    View body = inflater.inflate(R.layout.rsb_item_edit_text_compact, parent, false);

    editText = (EditText) body.findViewById(R.id.value);
    if (step.getPlaceholder() != null) {
        editText.setHint(step.getPlaceholder());
    } else {
        editText.setHint(R.string.rsb_hint_step_body_text);
    }

    TextView title = (TextView) body.findViewById(R.id.label);

    if (viewType == VIEW_TYPE_COMPACT) {
        title.setText(step.getTitle());
    } else {
        title.setVisibility(View.GONE);
    }

    // Restore previous result
    String stringResult = result.getResult();
    if (!TextUtils.isEmpty(stringResult)) {
        editText.setText(stringResult);
    }

    // Set result on text change
    RxTextView.textChanges(editText).subscribe(text -> {
        result.setResult(text.toString());
    });

    // Format EditText from TextAnswerFormat
    TextAnswerFormat format = (TextAnswerFormat) step.getAnswerFormat();

    editText.setSingleLine(!format.isMultipleLines());

    if (format.getMaximumLength() > TextAnswerFormat.UNLIMITED_LENGTH) {
        InputFilter.LengthFilter maxLengthFilter = new InputFilter.LengthFilter(format.getMaximumLength());
        InputFilter[] filters = ViewUtils.addFilter(editText.getFilters(), maxLengthFilter);
        editText.setFilters(filters);
    }

    Resources res = parent.getResources();
    LinearLayout.MarginLayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.leftMargin = res.getDimensionPixelSize(R.dimen.rsb_margin_left);
    layoutParams.rightMargin = res.getDimensionPixelSize(R.dimen.rsb_margin_right);
    body.setLayoutParams(layoutParams);

    return body;
}
 
Example 20
Source File: DecimalWidget.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
public DecimalWidget(Context context, FormEntryPrompt prompt, boolean secret, boolean compact) {
    super(context, prompt, secret, compact);

    // formatting
    mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontSize);
    mAnswer.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_ACTION_NEXT);

    // needed to make long readonly text scroll
    mAnswer.setHorizontallyScrolling(isInCompactMode());

    // only numbers are allowed
    mAnswer.setKeyListener(new DigitsKeyListener(true, true));

    // only 15 characters allowed
    InputFilter[] fa = new InputFilter[1];
    fa[0] = new InputFilter.LengthFilter(15);
    mAnswer.setFilters(fa);

    Double d = null;
    if (getCurrentAnswer() != null) {
        d = (Double)getCurrentAnswer().getValue();
    }

    NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
    nf.setMaximumFractionDigits(15);
    nf.setMaximumIntegerDigits(15);
    nf.setGroupingUsed(false);
    if (d != null) {
        Double dAnswer = (Double)getCurrentAnswer().getValue();
        String dString = nf.format(dAnswer);
        dString = dString.replace(',', '.');
        mAnswer.setText(dString);
    }

    // disable if read only
    if (prompt.isReadOnly()) {
        setBackgroundDrawable(null);
        setFocusable(false);
        setClickable(false);
    }
}