如何在视图中显示动态字符串?

时间:2014-09-18 17:41:14

标签: java android string.format

例如,我想显示设备上次与其他设备同步的日期时间/字符串。我现在有这样的事情:

        Resources resources = context.getResources();
        String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);

我将资源字符串保存在我的values / strings.xml中:

<string name="last_sync">Last synced  %s</string>

在我的活动视图中,我有以下内容:

 <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="@string/last_sync"
            />

但我运行设备时只显示字符串表示法。

我做错了什么?它应该显示日期时间的字符串而不是占位符。

例如,我硬编码了我的字符串:

String fileLastSync = "09-18-2014";

我的输出:

上次同步:%s

我的预期输出:

上次同步:2014年9月9日

3 个答案:

答案 0 :(得分:1)

这样做:

<TextView
            android:id="@+id/tvLastSync"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="@string/last_sync"
            />

现在进入Activity更新tvLastSync

   tvLastSync=(TextView)findViewById(R.id.tvLastSync);
   String syncString = String.format(getResources().getString(R.string.last_sync), fileLastSync);
    System.out.println(syncString);
    tvLastSync.setText(syncString);

答案 1 :(得分:1)

下面,

<TextView
        android:id="@+id/last_sync" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="@string/last_sync"
        />

然后在onCreate()中输入以下内容:

Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);

TextView lastSyncTextView = ( (TextView) findViewById(R.id.last_sync) );

lastSyncTextView.setText(syncString);

答案 2 :(得分:0)

看起来你可以使用getString(int id,Object ... formatArgs)。尝试使用原始代码将fileLastSync作为formatArg传递。