I’m an amateur developer creating a short app and I’m having trouble using both the XML file for a particular activity along with Activity’s Java method “setContentView”. I need the method because I am generating numbers from a computation and the number generated is variable depending on different parameters. Therefore, each time I call the computation I have to call:
textView.setText(message + " is " + output);
setContentView(textView);
But I also created several buttons on the Activity’s XML page which I would also like to show up on the Activity’s page. For example, this is one of the buttons I created:
<Button
android:layout_marginTop="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_quit"
android:onClick=".quit" />
However, if I call:
setContentView(R.layout.activity_compute_number);
after the set content view for the variable text message I mentioned earlier, the XML file overrides the text message and the text message never shows up and vice versa if I call the two setContentView methods the other way around. How do I get them both to render on the Activity screen simultaneously?
In your activity_compute_number.xml, you should assign an id to your button and textview. This way you can reference your button and textView.
Notice the android:id=”@+id/button_compute” and android:id=”@+id/textView_answer”. This gives this button and textview id’s called button_compute and textView_answer respectively.
Then change your onCreate to the following:
In onCreate() method you set your view to show the layout in your activity_compute_number.xml by calling setContentView() only once. You reference your button and textview by findViewById specifying the id’s you have set in your xml.