2

そのコードに問題があります

setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");

アクティビティ内にある場合は機能しますが、そうでない場合は、明らかにエラーが発生します。

The method findViewById(int) is undefined for the type new TimerTask(){}
The method setContentView(int) is undefined for the type new TimerTask(){}

コードは別のクラス(アクティビティではない)のタイマー内にあります。完全なコードは次のとおりです。

//main timer task for ingame time processing
static Timer gameTimer = new Timer();
static TimerTask gameTimerTask = new TimerTask() {
    @Override
    public void run() {
        setContentView(R.layout.game);
        TextView text = (TextView) findViewById(R.id.qwe_string);
        text.setText("Hello Android");
    }
};

そのように変えてみました

ScreenGame.this.setContentView(R.layout.game);
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android");

しかし、それでも機能しません:(

PS-はい、私は他の同様の質問を検索しましたが、それらはすべて同じように見えますが、実際には完全に異なります。

4

2 に答える 2

2
ScreenGame.this.setContentView(R.layout.game);
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android");

とまったく同じです

setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");

不正なコード

他のすべてのアクティビティを起動する親クラスを作成する必要があります。その親クラスでは、各子アクティビティへの参照を持ち、各子にそのテキストフィールドを要求できます。

// In the parent:
child.getTextView().setText("Hello galaxy!");

// with the child method:
TextView getTextView () {
  return (TextView) findViewById(R.id.qwe_string);
}

編集:詳細:

私が与えたコードは良くありませんでした、私はあなたの問題をよく理解していませんでした...私は今私がそうすることを望みます、私は自分自身を修正しようとしますか?

たとえばMyTimer、クラスを拡張する別のTimerTaskクラスを作成します。

class MyTimer extends TimerTask {
  // your class
}

引数としてTextViewを除いて、コンストラクターを作成し、それへの参照を保存します。

TextView theTextView;
MyTimer (TextView tv) {
  this.theTextView = tv;
}

今実装しますrun()

@Override
public void run() {
    setContentView(R.layout.game);
    thetextView.setText("Hello Galaxy!");
}

次のコードを使用して、makeこのクラスを呼び出します。

static TimerTask gameTimerTask = new MyTimer((TextView) findViewById(R.id.qwe_string));

これがすべて正しいことを願っています。テスト環境がないため、メモリからこれを実行する必要があります。少なくともそれは正しい方向にあなたを助けるはずです。

于 2012-05-26T10:12:19.337 に答える
0

必要になるだろう:

ScreenGame.this.runOnUiThread( new Runnable(){
  public void run(){
   TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
   text.setText("Hello Android");  }
 });

そして、次の行を呼び出す必要がありonCreate()ますScreenGame

setContentView(R.layout.game);
于 2012-05-26T10:10:32.727 に答える