Reputation: 1746
I am working on the Android guide here: http://developer.android.com/training/basics/activity-lifecycle/starting.html and there is reference to a variable that has never been created
mTextView = (TextView) findViewById(R.id.text_message);
Where am I supposed to define text_message?
Thanks for your help!
Update: I believe the chunk of code from which this is taken is merely an example, and not to be incorporated with the application we created in the previous part of the tutorial.
Upvotes: 0
Views: 1217
Reputation: 44571
It is declared here
TextView mTextView; // Member variable for text view in the layout // Right here
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Declaring it outside of a method, generally right after class declaration, makes it a member variable so it can be used anywhere in the class, including inner classes and listeners. You just can't initialize it in the same place because you haven't inflated
your Layout
yet by calling setContentView()
Short example
public class MyActivity extends Activity
{
TextView mTextView; // Member variable for text view in the layout
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the user interface layout for this Activity
// The layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message); // findViewById) looks for the id you set in the xml file, here text_message
}
R.id.text_message
is defined in the main_activity.xml
which could look something like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_message" <!-- this is where the R.id.text_message comes from -->
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"/>
</LinearLayout>
That documentation is definitely good to go through but you may want to start Here and go through a short example starting from creating a project
Upvotes: 1
Reputation: 7082
use this way define the xml layout inside the folder of res/layout/main.xml and set in setconentView.
private TextView mTextView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text_message);
mTextView.setText("Hello");
}
Upvotes: 0