为什么添加一个空字符串会修复我的TextView.setText()? [英] Why does adding an empty string fix my TextView.setText()?

查看:215
本文介绍了为什么添加一个空字符串会修复我的TextView.setText()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的应用,该应用在显示时增加了3个,只是使我感到困惑,这在我的手机中不起作用并显示了一些错误.

i'm trying to make a simple app which adds 3 in display,just got confused in one part this doesn't work in my phone and showing some error.

public void addThreeToTeamA(View view) {
        ScoreOfTeamA = ScoreOfTeamA + 3;
        displayScore(ScoreOfTeamA);
  }

  public void displayScore(int score){
     TextView text = findViewById(R.id.display_TeamA_score);
  text.setText(score);

这很好用

public void addThreeToTeamA(View view) {
            ScoreOfTeamA = ScoreOfTeamA + 3;
            displayScore(ScoreOfTeamA);
      }

      public void displayScore(int score){
         TextView text = findViewById(R.id.display_TeamA_score);
      text.setText("" + score);

"在最后一行做什么以使应用正常工作?

这是xml文件

  <TextView
            android:id="@+id/display_TeamA_score"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/_0"
            android:textSize="48sp"
            android:textAlignment="center" />

 <Button
            android:onClick="addThreeToTeamA"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/AddThree"
            android:layout_marginLeft="14dp"
            android:layout_marginRight="14dp"
            android:textSize="18sp"
            android:textAlignment="center" />

这不是完整的代码,它只是重要的部分.

推荐答案

score的类型为int.您要使用的setText方法应使用char[]类型的字符,即字符串.请注意,另一个setText方法确实需要一个整数,该整数用于通过其ID查找资源.这就是为什么使用setText(score)时不会出现错误的原因.

score is of type int. The setText method that you want to use expects something of type char[], i.e, a string. Note that another setText method does expect an integer, which is used to find a resource through its ID. This is why you don't get an error when using setText(score).

知道这一点:

  • text.setText(score);上,如果将score转换为字符串,则它将起作用(例如,使用Integer.toString(score)).
  • text.setText("" + score);上,您已经具有""字符串,并且Java理解您正在尝试将整数添加到字符串,因此它返回一个字符串.但是,此版本效率不高,因为每次将某些内容连接到字符串时,您都在创建新的字符串(这就是人们使用StringBuilder的原因.)
  • On text.setText(score);, if you convert score to a string, it will work (for instance, using Integer.toString(score)).
  • On text.setText("" + score);, you already have the "" string, and Java understands that you're trying to append an integer to a string, so it returns a string. This version, however, is not efficient, since everytime you concatenate something to a string, you're creating a new string (this is why people use StringBuilder).

长话短说,只需将score转换为字符串即可.

Long story short, just convert score to a string.

这篇关于为什么添加一个空字符串会修复我的TextView.setText()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆