活动Activity——为活动补充附加信息——利用资源文件配置字符串

 

 

 

 

res\values\strings.xml可用来配置字符串形式的参数。配置的字符串参数例子如下:

<string name="weather_str">晴天</string>

 

在活动页面的Java代码中,调用getString方法即可根据“R.string.参数名称”获得指定参数的字符串值。

 

获取代码示例如下:


// 显示字符串资源
private void showStringResource()

{
             // 从strings.xml获取名叫weather_str的字符串值
            String value = getString(R.string.weather_str);


            // 在文本视图上显示文字
            tv_resource.setText("来自字符串资源:今天的天气是"+value);
}

 

 

 

 

 

================================================================================================

 

 

 

 

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_resource"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:gravity="center"
        android:textColor="#000000"
        android:textSize="17sp" />

</LinearLayout>

 

 

 

 

 

 

 

 

 

 

 

 

package com.example.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{

    private TextView tv_resource; // 声明一个文本视图对象

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // 从布局文件中获取名叫tv_resource的文本视图
        tv_resource = findViewById(R.id.tv_resource);
        showStringResource(); // 显示字符串资源
    }

    // 显示字符串资源
    private void showStringResource()
    {
        String value = getString(R.string.weather_str); // 从strings.xml获取名叫weather_str的字符串值
        tv_resource.setText("来自字符串资源:今天的天气是"+value); // 在文本视图上显示文字
    }
}

 

 

 

 

 

 

 

 

 

 

 

<resources>
    <string name="app_name">My Application</string>
    <string name="weather_str">晴天</string>
    <string name="first_short">first</string>
    <string name="first_long">启停活动</string>
    <string name="second_short">second</string>
    <string name="second_long">来回跳转</string>
    <string name="third_short">third</string>
    <string name="third_long">登录返回</string>
</resources>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2022-07-09 14:09  小白龙白龙马  阅读(35)  评论(0编辑  收藏  举报