Android InputType layout parameter - how to allow

2019-01-22 11:04发布

I have a layout which has three fields for the entry of three map coordinates. So far so good. I'm using android:inputType="numberDecimal" in the layout. When entering the field the user gets the numeric keypad. Still good.

However, when a negative coordinate needs to be entered, there is no apparent way to do this.

23.2342 works fine. 232.3421 works fine. -11.23423 can not be entered - there is no way to enter the leading negative sign, or even wrap the coordinate in ().

I'm sure I can go the route of changing this to straight text inputType, and then use a regular expression to validate that what was entered is in fact a numeric coordinate, handle error messaging back to the user, etc. But I'd rather not go that route.

I have Googled and Stackoverflowed this question for a couple hours with no luck. Any suggestions?

8条回答
啃猪蹄的小仙女
2楼-- · 2019-01-22 11:40

Please use this code

 et.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_CLASS_NUMBER);
查看更多
我命由我不由天
3楼-- · 2019-01-22 11:41

Ended up using Pattern and Matcher for each of the axes, leaving the actual text input format open.

Three axes fields, submit button triggers onSave. Fields are validated and either the insert occurs, or error message is raised to submitter about required format for the Axes fields. Proper format is 1-3 digits, optionally prefaced by '-', optionally followed by '.' and additional digits.

Try this code :

private View.OnClickListener onSave=new View.OnClickListener(){
    public void onClick(View v){
        Pattern xAxis = Pattern.compile("[-+]?([0-9]*\\.)?[0-9]+");
        Matcher mForX = xAxis.matcher(xaxis.getText().toString());

        Pattern yAxis = Pattern.compile("[-+]?([0-9]*\\.)?[0-9]+");
        Matcher mForY = yAxis.matcher(yaxis.getText().toString());

        Pattern zAxis = Pattern.compile("[-+]?([0-9]*\\.)?[0-9]+");
        Matcher mForZ = zAxis.matcher(zaxis.getText().toString());

        //If Axis X and Axis Y and Axis Z are all valid entries, the proceed.
        if(mForX.find() && mForY.find() && mForZ.find()){
             //handle insert or update statement here
        }else{
             //give error message regarding correct Axis value format
        }
   }

}

查看更多
登录 后发表回答