Android TextView : “Do not concatenate text displayed with setText”

前端 未结 10 1490
小鲜肉
小鲜肉 2020-12-02 04:01

I am setting text using setText() by following way.

prodNameView.setText(\"\" + name);

prodOriginalPriceView.setText(\"\" + String.format(g         


        
相关标签:
10条回答
  • 2020-12-02 04:38

    You should check this thread and use a placeholder like his one (not tested)

    <string name="string_product_rate_with_ruppe_sign">Price : %1$d</string>
    
    String text = String.format(getString(R.string.string_product_rate_with_ruppe_sign),new BigDecimal(price).setScale(2, RoundingMode.UP));
    prodOriginalPriceView.setText(text);
    
    0 讨论(0)
  • 2020-12-02 04:39

    You can use this , it works for me

    title.setText(MessageFormat.format("{0} {1}", itemList.get(position).getOppName(), itemList.get(position).getBatchNum()));
    
    0 讨论(0)
  • 2020-12-02 04:40

    Don't Mad, It's too Simple.

    String firstname = firstname.getText().toString();
    String result = "hi "+ firstname +" Welcome Here";
                mytextview.setText(result);
    
    0 讨论(0)
  • 2020-12-02 04:46

    Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.

    <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
    

    using getString(R.string.welcome_message, "Test", 0);

    android will return a String with

     "Hello Test! you have 0 new messages"
    

    About setText("" + name);

    Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.

    0 讨论(0)
  • 2020-12-02 04:51

    the problem is because you are appending "" at the beginning of every string.

    lint will scan arguments being passed to setText and will generate warnings, in your case following warning is relevant:

    Do not build messages by concatenating text chunks. Such messages can not be properly translated.

    as you are concatenating every string with "".

    remove this concatenation as the arguments you are passing are already text. Also, you can use .toString() if at all required anywhere else instead of concatenating your string with ""

    0 讨论(0)
  • 2020-12-02 04:51
    prodNameView.setText("" + name); //this produce lint error
    
    val nameStr="" + name;//workaround for quick warning fix require rebuild
    prodNameView.setText(nameStr);
    
    0 讨论(0)
提交回复
热议问题