Number range on an edittext - only want numbers be

2019-09-17 05:56发布

I'm trying to make an app that only allows a user to enter between 1 and 10, I've tried writing my own method where if the number is out of that range, it changes the text views to ERROR and clears what's in the edit text, however it crashes the app. Does anyone know what's wrong with it? New to android.

Code:

    public void buttonClick (View v)
{



    TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
    TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
    TextView tvNameEnt = (TextView) findViewById(R.id.NameEnt);
    TextView tvNumEnt = (TextView) findViewById(R.id.NumEnt);

    EditText num = (EditText) findViewById(R.id.ETnumber);
    EditText name = (EditText) findViewById(R.id.ETname);

    String nameContent = name.getText().toString();
    String numContent = num.getText().toString();

    tvName.setText(nameContent);

        int value = Integer.parseInt(num.getText().toString());
        if (value > 10)
        {
            tvNum.setText("ERROR");
            num.getText().clear();
            name.getText().clear();

        }
        else if (value < 1)
        {
            tvNum.setText("ERROR");
            num.getText().clear();
            name.getText().clear();
        }
        else
        {



            tvNum.setText(numContent);

            tvNameEnt.setVisibility(View.VISIBLE);
            tvNumEnt.setVisibility(View.VISIBLE);
            tvName.setVisibility(View.VISIBLE);
            tvNum.setVisibility(View.VISIBLE);
        }

}

2条回答
聊天终结者
2楼-- · 2019-09-17 06:46

The main problem here is that you are trying to get the number in the edittext with: num.toString(), instead you have to use: num.getText().toString()

查看更多
家丑人穷心不美
3楼-- · 2019-09-17 06:50

You have issue on this line

int value = Integer.parseInt(num.toString());

change to:

int value = Integer.parseInt(num.getText().toString());

Now you call toString() method from Object for EditText object. You have to call getText() method for it as first and after then call toString() method for CharSequence

UPDATE: You find two times the same view with the same ids. Look at the code below:

TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
TextView tvName = (TextView) findViewById(R.id.tvNumEnt);

there should be R.id.tvNumEnt in the second time, I think so...

TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
查看更多
登录 后发表回答