在 TextView 中设定义在xml档中有帯参数的字符串
发布时间:2020-12-16 04:59:52 所属栏目:百科 来源:网络整理
导读:之前一直没想到使用这种方法耒设 TextView 要显示的字符串,所以就学习了一下: string.xml: 只有一个变数的话,就用 %s 代表你要用值替换的字符串,而当有多个的时候,便是采用 %1$s 代表第一个要替换的, %2$s 第二个。。。依此类推 而 % 是 escape 符号 s
之前一直没想到使用这种方法耒设 TextView 要显示的字符串,所以就学习了一下: string.xml: 只有一个变数的话,就用 %s代表你要用值替换的字符串,而当有多个的时候,便是采用 %1$s代表第一个要替换的,%2$s第二个。。。依此类推 而 % 是 escape 符号 <string name="loading_with_percent">加载中 %s%%</string> <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">String</string> <string name="action_settings">Settings</string> <string name="example1">本月薪资:%s元</string> <string name="example2">本薪:%1$s元,分红:%2$s元,报销:%3$s元</string> </resources> 相关api方法请参考这个 API,然後在代码中如此调用: package com.example.string; import android.os.Bundle; import android.app.Activity; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv1 = (TextView) findViewById(R.id.example1); TextView tv2 = (TextView) findViewById(R.id.example2); tv1.setText(getResources().getString(R.string.example1,1000)); tv2.setText(getResources().getString(R.string.example2,600,300,100)); } }
完整代码: https://github.com/shanwu/shanwu_coding_base/tree/StringExample (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |