我是android deva和java的新手。我想显示文字,但下面的代码不起作用。
DisplayText.java
package com.example.DisplayText;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class DisplayText extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv2 = (TextView) this.findViewById(R.id.thetext);
tv2.setText("YO -- ");
setContentView(R.layout.main);
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:id="@+id/thetext"
/>
</LinearLayout>
非常感谢您的帮助! :)
答案 0 :(得分:2)
更改此代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv2 = (TextView) this.findViewById(R.id.thetext);
tv2.setText("YO -- ");
setContentView(R.layout.main);
}
这一个:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv2 = (TextView) this.findViewById(R.id.thetext);
tv2.setText("YO -- ");
}
答案 1 :(得分:1)
把
setContentView(R.layout.main);
之前TextView tv2 = (TextView) this.findViewById(R.id.thetext);
从main.xml访问TextView