Android中String的处理
1、在Android中显示的字符串,最好放到values/strings.xml文件中,这样的话,易于管理
2、在values/strings.xml中得到的字符串,可以格式化后显示到界面上
实例代码:
main.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
android:layout_height="fill_parent">
values/strings.xml文件
<?xml version="1.0" encoding="utf-8"?>
java代码
package yyl.strings;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class StringsActivity extends Activity {
// 定义变量
private EditText name = null;
private TextView result = null;
private Button btnFormat = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 根据Id得到控件对象
name=(EditText)findViewById(R.id.name);
result=(TextView)findViewById(R.id.result);
btnFormat = (Button) findViewById(R.id.format);
//给按钮添加单击事件监听器
btnFormat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
applyFormat();
}
});
}
/*
* 使用指定的格式字符串和参数返回一个格式化字符串
*/
public void applyFormat()
{
//得到格式化字符串
String format = getString(R.string.funky_format);
//根据格式化字符串输出格式化以后的字符,格式化的字符串是My name is <b>%1$s</b>
String simpleResult = String.format(format, TextUtils.htmlEncode(name.getText().toString()));
//显示到页面
result.setText(Html.fromHtml(simpleResult));
}
}
更多相关文章
- 修改Android中strings.xml文件
- 2013.07.22(2)——— android 验证码与cookie
- 申请Android(安卓)Map 的API Key(v2)的最新申请方式(SHA1密钥)
- Android下如何计算要显示的字符串所占的宽度和高度
- Android: R cannot be resolved to a variable
- Android培训班(46)
- Android(安卓)网络请求加密
- cocos2d-x 从C++调Java
- Eclipse环境下格式化Android的代码风格