0

我在我的佈局文件夾中創建了一個名爲game.xml的新.xml文件。它包含一個TextView。從MainAcivity.java更新不同佈局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); 

} 
    ... 

我嘗試了這種方式。但它不起作用。任何人都可以幫助我?

回答

1

你不能設置視圖,TextView這裏,尚未通過吹氣或setContentView()充氣佈局創建。您可以通過Intent傳遞值到類,將實際使用TextView

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

哪裏NextActivity是,將顯示的TextView

然後你就可以得到該值,並將其設置在你的其他活動活動

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

你已經在你的第二個活動onCreate()使用setContentView(R.layout.game);

0

Short Answer,No

佈局文件只是一個藍圖。實際的文本視圖直到佈局已經膨脹(變成視圖)纔會存在。

我的問題,(你)是不是使用這個game.xml?它是否在另一項活動?