2012-08-16 69 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));