【问题标题】:How to set XML string after concat'ing in Java?在 Java 中连接后如何设置 XML 字符串?
【发布时间】:2014-07-03 21:42:55
【问题描述】:

所以我按照文档here 将 XML 字符串值与其他内容连接起来,结果得到以下代码:

//XML strings.xml
<string name="start_next_act_string">The next activity has been scheduled to automatically launch in %1$d seconds!</string>

//layout/activity_home.XML
    <TextView
        android:text="@string/start_next_act_string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

//Home.java inside class, but outside oncreate
int startNextActivityInSeconds = 10;

//Home.java inside class and inside oncreate
        super.onCreate(savedInstanceState);

        Resources res = getResources();
        String text = String.format(res.getString(R.string.start_next_act_string), startNextActivityInSeconds);

        setContentView(R.layout.activity_home);

但在 Android 屏幕上会打印出来

下一个活动已安排在 %1$d 秒后自动启动!

而不是

下一个活动已安排在 10 秒后自动启动!

如何更新 XML 字符串以显示连接后的字符串结果?

【问题讨论】:

    标签: java android xml string concatenation


    【解决方案1】:

    恐怕您尝试做的事情不起作用。当布局膨胀时,字符串完全按照资源文件中的定义使用。

    为此,您必须明确设置文本,即

    setContentView(R.layout.activity_home);
    TextView tv = (TextView)findViewById(R.id.theId);
    tv.setText(text);
    

    其中“theId”是您必须在 xml 文件中为 TextView 设置的 id,例如:

    <TextView
        android:id="@+id/theId"
        android:text="@string/start_next_act_string"
        ...
    

    【讨论】:

      【解决方案2】:

      您需要将 TextView 的 text 属性设置为您创建的新字符串,否则格式化后的字符串将单独存储在您的本地字符串中,不会反映在 UI 中。

      首先你需要通过给它一个 ID 来命名你的 TextView:

      <TextView
          android:id="@+id/YourId"
          ...
      

      然后,从您的Activity 绑定到视图并主动修改其文本:

      TextView myTextView = (TextView)findViewById(R.id.YourId);
      myTextView.setText(text);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-18
        • 2011-03-11
        • 1970-01-01
        • 2012-01-04
        • 2016-06-26
        • 1970-01-01
        • 1970-01-01
        • 2013-03-15
        相关资源
        最近更新 更多