从MainAcivity.java更新不同布局xml的textview?

时间:2013-02-13 22:35:33

标签: android android-layout android-emulator android-widget textview

我在我的布局文件夹中创建了一个名为game.xml的新.xml文件。它包含TextView。

是否可以在我的主要活动中设置位于game.xml中的textview上的文本?

game.xml(Textview部分)

<TextView
    android:id="@+id/tV1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_centerVertical="true"
    android:text="TextView" />

MainActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setImageArray();
    String actualword = chooseWord(words);
    createLetterArray(actualword);
    TextView textView1 = (TextView) findViewById(R.id.tV1); //get a reference to the textview on the game.xml file.
    textView1.setText(actualword);

}
    ...
我试过这种方式。但它不起作用。谁可以帮助我?

2 个答案:

答案 0 :(得分:1)

您无法在此处设置视图,TextView,而不是通过inflater或setContentView()来扩充布局。您可以通过Intent将值传递给实际使用TextView

的类
Intent intent = new Intent(MainActivity.this, NextActivity.class); 
intent.putExtra("key", actualword);
startActivity(intent);

NextActivity是显示文本视图的活动

然后你可以获得该值并在其他活动中设置

Intent recIntent = getIntent();
String text = recIntent.getStringExtra("key");
TextView textView1 = (TextView) findViewById(R.id.tV1); //get a reference to the textview on the game.xml file.
textView1.setText(text);

在第二项活动setContentView(R.layout.game);中使用onCreate()之后

答案 1 :(得分:0)

简答,否

布局文件只是一个蓝图。在布局膨胀(变成视图)之前,实际的文本视图不存在。

我的问题,(如何)你没有使用这个game.xml?是否在另一项活动中?