2012-02-24 13 views
0

私はAndroidが初めてです。私は実行するためにいくつかのコードをダウンロードしましたが、問題がある:Android helloWorld with button

package t.t.t4; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class Test4Activity extends Activity { 
    /** Called when the activity is first created. */ 
    OnClickListener listener1 = null; 
    Button button1; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     listener1 = new OnClickListener() { 
      public void onClick(View v) { 
       TextView text_view = (TextView) findViewById(R.id.TextView01); 
       CharSequence text_view_old = text_view.getText(); 
       text_view.setText("Before: "+ text_view_old +"\nAdded information: Hello World again !"); 
      } 
     }; 

     setContentView(R.layout.main); 
     button1 = (Button) findViewById(R.id.Button01); 
     button1.setOnClickListener(listener1); 
    } 
} 

R.id.TextView01は、エラーが発生しましたラインです。 RとR.idの意味は何ですか?

+0

ここにmain.xmlを入れてください。 –

+0

こちらのエラーをどうぞよろしいですか? –

+0

[XMLレイアウト](http://developer.android.com/guide/topics/ui/declaring-layout.html)ガイドを読んだことがありますか? –

答えて

2

super.onCreate();の後にsetContentView(R.layout.main);を追加する必要があります。すべてのウィジェットがレイアウトファイルで宣言されているため、最初に読み込む必要があります。ここでtextviewmain.xmlファイルで宣言されています。

これは、ビューを設定する前にそのテキストビューを使用するため、エラーが発生するのはそのためです。

main.xmlファイルにtexview with id TextView01と宣言する必要があります。

+1

OPは設定前にテキストビューを使用していません。参照はOnClickListenerにあり、クリックがあるまで実行されません。 –

+0

そしてBTWは何をしていますか?彼のコードを見てください? –