1

これについていくつか質問があることは知っていますが、まだわかりません。活動があります

package test.example.om;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import test.example.om.Texter;

public class TextActivity extends Activity {
   /** Called when the activity is first created. */

    public String text="Helloo";
    @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Texter myTexter = new Texter(); 
       myTexter.textTexter();


   }
    public void textSet(){
        TextView tv = (TextView) findViewById(R.id.myTextViewInXml);
           tv.setText(text);
}
}

そして、クラス Texter

package test.example.om;

import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Texter extends Activity{
String string="Helloo";


public void textTexter(){
    TextView tv = (TextView) findViewById(R.id.myTextViewInXml);
       tv.setText(string);
}
}

LogCat に NullPointerException が表示され、アプリがクラッシュします。メインアクティビティクラス以外のクラスからTextViewにテキストを設定するにはどうすればよいですか?

4

1 に答える 1

3

アクティビティ サブクラスをインスタンス化していますが、それを行うべきではありません...また、正しいアクティビティ ライフサイクルを経ていないため、コンテキストが null のときに (Texter クラスで)ViewById を見つけようとしています。

テキスト ビューのテキストを変更するには、textTexter メソッドを Texter から TextActivity に移動して呼び出すだけです。Texter アクティビティは使用されていないため削除します。

package test.example.om;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import test.example.om.Texter;

public class TextActivity extends Activity {
   /** Called when the activity is first created. */

    public String text="Helloo";
    @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       TextView tv = (TextView) findViewById(R.id.myTextViewInXml);
       tv.setText(text);


   }

}

編集:別のクラスからやりたいことに気づきました。これを行うには、変更したいテキストビューへの参照を与え、それに setText を設定するだけです

于 2011-08-29T18:31:53.443 に答える