使用activity_main.xml中MainActivity.java的字符串

时间:2013-09-29 09:32:44

标签: android

我在MainActivity.java中定义了一个字符串:

public String counter1 = String.valueOf(e.getCount());

我想在activity_main.xml中使用此字符串:

android:text="@string/counter1"

正如您所知,我对此非常陌生,所以基本的步骤将会受到赞赏。

由于

4 个答案:

答案 0 :(得分:1)

简短的回答:你做不到。您在xml布局中设置的资源必须在资源文件中静态定义,例如.-

<string name="counter1">COUNTER VALUE</string>

要动态定义新字符串,必须以编程方式设置它们.-

TextView textView = (TextView) findViewById(R.id.textViewId);
textView.setText(counter1);

答案 1 :(得分:1)

如果你能让它发挥作用,你想做什么?如果要动态设置文本,可以使用setText

yourTextView.setText(counter1);

答案 2 :(得分:0)

如果你想以编程方式设置一些你可以使用的东西......你应该使用

txtview.setText(yourString);

如果要在XML中设置String,则可以像在XML中一样在

中设置它
  android:text="Exercise Name"

或使用字符串,然后您也可以以编程方式使用 在字符串中:

   <string name="Delete">Delete</string>

在代码中,您可以使用R.string.Delete或getString(R.string.app_name)调用它;

当然你也可以使用@string ...

从XML中设置字符串

根据您要做的事情的声音,您希望在程序运行时更改TextView,以便第一个选项适合您

答案 3 :(得分:0)

你不能,如果你想实现这种解决方案: 在strings.xml中创建字符串

<string name="counter1">value of counter</string>

如果你想动态设置计数器的文本,那么在你的活动中:

TextView tView = (TextView) findViewById(R.id.textViewId);
tView.setText(counter1);

你应该遵循这个,因为所有静态字符串都应该在strings.xml中定义