Reputation: 187
I've created a new .xml file in my layout folder called game.xml. It contains an TextView.
Is it possible to set the text on the textview located in the game.xml from my main activity?
game.xml (Textview part)
<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);
}
...
I tried it this way. But it doesn't work. Anyone who can help me ?
Upvotes: 0
Views: 1603
Reputation: 44571
You can't set a view, TextView
here, that hasn't been created by inflating the layout through an inflater or setContentView()
. You can pass the value through an Intent
to the class that will actually use the TextView
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("key", actualword);
startActivity(intent);
Where NextActivity
is the activity that will display the textview
Then you can get that value and set it in your other activity
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);
After you have used setContentView(R.layout.game);
in onCreate()
of your second activity
Upvotes: 1
Reputation: 1315
Short Answer, No
The layout file is just a blueprint. The actual textview doesn't exist until the layout has been inflated (turned into the views).
My question, (how) are you're not using this game.xml? Is it in another activity?
Upvotes: 0