Reputation: 3137
I'm completely new to Android application programming, and I was reading through Google's tutorial: http://developer.android.com/training/basics/firstapp/starting-activity.html.
On this page, under the "Display the Message" section, they create TextView
object, and use setContentView
with the textView
object as the argument, to display some text. I was wondering, if I'm understanding correctly, instead of creating the TextView
object within the code, can you define it in XML instead? If you define it in XML, would that require you to create a new XML file besides main_activity.xml? Thanks.
Upvotes: 0
Views: 3649
Reputation: 12487
You can declare all your layouts and views inside a xml. For the given example, the code would look like the following
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set your parent view
setContentView(R.layout.main_layout);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Get the reference to the TextView and update it's content
TextView textView = (TextView)findViewById(R.id.my_text_view);
textView.setText(message);
}
And your main_layout.xml would look like
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:id="@+id/my_text_view"/>
Upvotes: 1
Reputation: 82355
You can arbitrarily create view files (XML files) and specify the primary type of the view and the children it contains. You could create the TextView
element within the main_activity.xml view and find it by the relative Id.
That being said in the article in question if you want to have a separate view for just the TextView
element then you would likely need another XML file to define that view if you do not want to specify it programmatically.
In a standard application you will likely have a predefined view (XML file) that you will set as the content view and reference elements from within it (as well as possibly add new elements).
It is very flexible, in short to answer your question no, you do not need to generate a new XML view file, you could simply add a TextView
to an existing view file or specify it at runtime.
Upvotes: 0