要从应用程序的基本语言环境获取字符串资源,可以使用以下步骤:
Hello
World
String helloString = getResources().getString(R.string.hello);
String worldString = getResources().getString(R.string.world);
在上面的代码中,R.string.hello
和R.string.world
是自动生成的资源ID,它们分别对应于在strings.xml文件中定义的字符串资源。
helloString
和worldString
变量来访问你的字符串资源。textView.setText(helloString + " " + worldString);
上面的代码将在TextView中显示 "Hello World"。
这是一个完整的例子:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String helloString = getResources().getString(R.string.hello);
String worldString = getResources().getString(R.string.world);
TextView textView = findViewById(R.id.textView);
textView.setText(helloString + " " + worldString);
}
}
这是一个简单的示例,演示了如何从应用程序的基本语言环境获取字符串资源并在TextView中显示它们。你可以根据自己的需求进行修改和扩展。
上一篇:Android: 从相册选择照片