2011-05-20 17 views
0

私はアンドロイドのdevaとjavaを使い慣れました。私はテキストを表示するが、私のコードは動作しません。任意の助けAndroid:TextViewが動作しません

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> 

多くの感謝! :)

+2

どのレイアウトファイルを使用するのかを指定してから、そこからビューを取得する必要があります。上のコードでは、setContentViewの呼び出しの前にTextViewをフェッチしようとしています。 theText IDを持つTextViewを検索するシステムの指示がないため、これは機能しません。オーダーを変更してコンテンツビューを最初に設定すると、それが機能します。 – TofferJ

答えて

2

変更このコード:この1と

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

はmain.xmlからのTextViewにアクセスするためにTextView tv2 = (TextView) this.findViewById(R.id.thetext);

setContentView(R.layout.main); 

を置きます

関連する問題