package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
开发者_如何学Go TextView tv = new TextView(this);
tv.setText("Why did it say hello world?");
setContentView(R.layout.main);
}
}
I'm following the Hello, World tutorial on the android SDK site. When I set the text for tv, it never shows. Instead, the output is:
Hello World, HelloAndroid!
Where in the world is that coming from? I never wrote that text, ever, anywhere...freaky.
TextView tv = new TextView(this); << create TextView object
tv.setText("Why did it say hello world?"); << set text to it
setContentView(R.layout.main); << display the view defined in main.xml
as scriptocalypse said you can simply set the content view to tv, alternatively, and I think a better approach is to use the main.xml
:
in main.xml
there is a TextView
and it has a property called id
, it looks something like this: <TextView android:id="@+id/text"
you can use this id to get the TextView object of this xml like this:
setContentView(R.id.xml);
TextView tv = (TextView)findViewById(R.id.text);
tv.setText("Your text");
There are 3 things to remember:
R.id.text
is corresponding toandroid:id="@+id/text"
.R.id.text
is an integer, generated during the build of application, it's not a string, and cannot be manipulated as a string.setContentView
has to be called before callingfindViewById
, otherwise, you will get null as return value offindViewById
.
Check your main.xml
file. It's likely being printed from there.
To get your own test there, add your new TextView
to the main.xml
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Your text here" />
(Note: the "Your text here" should really be brought out to the strings.xml
file.)
To put in an editable text field, use an EditText
field.
<EditText android:id="@+id/TextId" android:hint="background text"
android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
You should use setContentView before creating a new TextView object. Also, did you remember to add the TextView to the display?
setContentView(tv)
I see you adding the xml layout, but you never add the newly created TextView
You are calling setContentView() and passing in a reference to a layout, specifically main.xml as noted by Haphazard. If you want to see your TextView that you just created, you should be able to pass the variable tv into the setContentView() method.
The default main.xml has a reference to a String in strings.xml in your res/ folder. In there is the definition of a String "Hello World", which is why you are seeing "Hello World".
精彩评论