2012-08-16 68 views
1

我目前正在爲android開發一款遊戲。我想在我的課gameView上添加一個textview。 這是我的代碼:在我的課上添加一個textView遊戲查看

類的main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 

android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 
<app.com.GameView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/game_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 
<TextView 
     android:id = "@+id/score_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="0" 
     android:paddingLeft="15dp" 
     /> 
</FrameLayout> 

這是課外活動:

public class GameActivity extends Activity { 

/** Called when the activity is first created. */ 
private app.com.GameView gameView ; 
private TextView scoreText; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    gameView = (app.com.GameView)findViewById(R.id.game_view); 
    scoreText = (TextView)findViewById(R.id.score_text); 
    gameView.setScoreText(scoreText); 
} 

這是CALSS GameView:

private int score = 0; 

private TextView scoreText; 

public void setscoreText(TextView tv){ 

this.scoreText = tv; 
} 

但是當我使用scoreText .setText(「」+分數),這是一個錯誤異常「CalledFromWrongThreadException:只有原點創建視圖層次結構的al線程可以觸及其視圖。「?請幫幫我?

+0

你說的 '不能用' 是什麼意思?嘗試調用setText時觀察到的任何異常? – sandrstar 2012-08-16 08:16:32

回答

1

試試這個:scoreText.setText(String.valueOf(score));

編輯:

我認爲你必須使用處理器類信息發送到與UI交互。 您在Android SDK樣例LunarLander中也有一個很好的例子,它也是一款遊戲。

我希望能幫到你。

+0

我嘗試做它,但它不成功 – 2012-08-16 09:56:28

1

你不能使用整數設置文本。

它首先需要轉換爲一個字符串。最簡單的方法是:

scoreText.setText(score + ""); 

scoreText.setText(Integer.toString(score));