简体   繁体   English

Android Studio中Java中的冗余字符串格式

[英]Redundant String Format in Java in Android Studio

I tried to update a TextView after button is clicked. 单击按钮后,我尝试更新TextView。 I used the Strings.xml to help me out and named it as "justice". 我使用Strings.xml来帮助我,并将其命名为“ justice”。 Unfortunately when I click the button, apparently that all text in "justice" is added twice. 不幸的是,当我单击按钮时,显然“ justice”中的所有文本都被添加了两次。 One with bold fonts and another without bold fonts. 一个使用粗体,另一个不使用粗体。

I tried added "%s", but it doesn't work either. 我尝试添加“%s”,但也不起作用。 I used Android Studio 3.3.0. 我使用的是Android Studio 3.3.0。

public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   tView = (TextView) findViewById(R.id.textView1);
   clickhere = (Button) findViewById(R.id.button1);

   clickhere.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
          String display = String.format(getString(R.string.justice, "%s"));
          tView.setText(display);
       }
   });
}

I expect to see only one copy of "justice" when I click the button. 当我单击按钮时,我预计只会看到一份“正义”的副本。 Does this bug comes from Android Studio or something is wrong with my code??? 此错误是来自Android Studio还是我的代码有问题??? Someone, help me please. 有人请帮帮我。 Thank you. 谢谢。

您应该可以这样设置文本:

tView.setText(getString(R.string.justice));
public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   // clean up code :)
   tView = findViewById(R.id.textView1);
   clickhere = findViewById(R.id.button1);

   clickhere.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
          tView.setText(R.String.justice);
       }
   });
}

First of all, check your strings.xml and make sure you do not have duplicate strings in justice. 首先,检查您的strings.xml并确保您没有多余的字符串。 If it does not, try the following 如果不是,请尝试以下操作

 public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   tView = (TextView) findViewById(R.id.textView1);
   clickhere = (Button) findViewById(R.id.button1);

   clickhere.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
          String display = getString(R.string.justice);
          tView.setText(display);
       }
   });
}

By the way, to get the reference to view objects, you do not need explicit casting. 顺便说一句,要获取对视图对象的引用,不需要显式强制转换。 The following is also fine. 以下也很好。

tView = findViewById(R.id.textView1);
clickhere = findViewById(R.id.button1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM