1、在Android中显示的字符串,最好放到values/strings.xml文件中,这样的话,易于管理

2、在values/strings.xml中得到的字符串,可以格式化后显示到界面上

 

实例代码:

 

main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

            android:layout_width="fill_parent" android:layout_height="wrap_content">
       
                    android:layout_height="wrap_content">
   

            android:layout_height="wrap_content">

 

values/strings.xml文件

<?xml version="1.0" encoding="utf-8"?>

    StringsDemo
    Name:
    My name is <b>%1$s</b>

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));
    }

}

更多相关文章

  1. 修改Android中strings.xml文件
  2. 2013.07.22(2)——— android 验证码与cookie
  3. 申请Android(安卓)Map 的API Key(v2)的最新申请方式(SHA1密钥)
  4. Android下如何计算要显示的字符串所占的宽度和高度
  5. Android: R cannot be resolved to a variable
  6. Android培训班(46)
  7. Android(安卓)网络请求加密
  8. cocos2d-x 从C++调Java
  9. Eclipse环境下格式化Android的代码风格

随机推荐

  1. Android学习目录
  2. Android 学习成品
  3. android点击文本框之外的地方隐藏键盘
  4. Android设置振铃
  5. Android(安卓)图片的加载与保存
  6. 改变Android中默认Dialog的样式
  7. android 2.2 eclipse
  8. Android开发实践 网络通信 URL、URLConne
  9. android editText 软键盘enter键图标的设
  10. Android debug.keystore的密码