Convert number in textview to int

前端 未结 5 1665
渐次进展
渐次进展 2021-02-13 10:27

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have r

相关标签:
5条回答
  • 2021-02-13 10:49
    TextView tv = (TextView)findviewbyID(R.id.textView);
    String text = tv.getText().toString();
    int n;
    if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
    {
       n = Integer.parseInt(text);
    }
    else
    {
       System.out.println("not a valid number");
    }
    
    0 讨论(0)
  • 2021-02-13 10:56

    You can read on the usage of TextView.

    How to declare it:

    TextView tv;
    

    Initialize it:

    tv = (TextView) findViewById(R.id.textView);
    

    or:

    tv = new TextView(MyActivity.this);
    

    or, if you are inflating a layout,

    tv = (TextView) inflatedView.findViewById(R.id.textView);
    

    To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.

    To get a value from tv use tv.getText().

    Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..

    String tvValue = tv.getText().toString();
    
    if (!tvValue.equals("") && !tvValue.equals(......)) {
        int num1 = Integer.parseInt(tvValue);
    }
    
    0 讨论(0)
  • 2021-02-13 10:58
    TextView tv = (TextView)findviewbyID(R.id.textView);
    int num = Integer.valueOf(tv.getText().toString());
    
    0 讨论(0)
  • 2021-02-13 11:04

    this code actually works better:

    //this code to increment the value in the text view by 1
    
    TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
            CharSequence v1=quantityTextView.getText();
            int q=Integer.parseInt(v1.toString());
            q+=1;
            quantityTextView.setText(q +"");
    
    
    //I hope u like this
    
    0 讨论(0)
  • 2021-02-13 11:08

    Here is the kotlin version :

    var value = textview.text.toString().toIntOrNull() ?: 0
    
    0 讨论(0)
提交回复
热议问题