how to get text from textview

前端 未结 5 1103
有刺的猬
有刺的猬 2020-12-01 13:40

if I have set text in textview in such way, which is not problem:

  tv.setText(\"\" + ANS[i]);

this simply getting from this way.



        
5条回答
  •  我在风中等你
    2020-12-01 14:27

    If it is the sum of all the numbers you want, I made a little snippet for you that can handle both + and - using a regex (I left some print-calls in there to help visualise what happens):

        final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
        final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
        Matcher matcher = pattern.matcher(string);
    
        System.out.print(string);
        System.out.print('\n');
        int sum = 0;
    
        while( matcher.find() ){
            System.out.print(matcher.group(1));
            System.out.print(matcher.group(2));
            System.out.print('\n');
            sum += Integer.parseInt(matcher.group(1)+matcher.group(2));
        }
        System.out.print("\nSum: "+sum);
    

    This code prints the following:

      5
    - 9
    + 5
    5
    -9
    5
    
    Sum: 1
    

    Edit: sorry if I misunderstood your question, it was a little bit unclear what you wanted to do. I assumed you wanted to get the sum of the numbers as an integer rather than a string.

    Edit2: to get the numbers separate from each other, do something like this instead:

        final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
        final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
        Matcher matcher = pattern.matcher(string);
        ArrayList numbers = new ArrayList();
    
        while( matcher.find() ){
            numbers.add(Integer.parseInt(matcher.group(1)+matcher.group(2)));
        }
    

提交回复
热议问题