苦苦于让一个简单的OnClickListener工作,

时间:2014-08-09 17:22:51

标签: java android

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;


public class HomeScreen extends Activity {

    LinearLayout background;
    Button btnRed, btnBlue, btnGreen;
    Boolean Red, Blue;
    Boolean Green = true;
    TextView player1Count, player2Count;
    int count1, count2;





    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);

        background = (LinearLayout) findViewById(R.id.background);
        btnRed = (Button) findViewById(R.id.btnRed);
        btnBlue =  (Button) findViewById(R.id.btnBlue);
        btnGreen =  (Button) findViewById(R.id.btnGreen);
        player1Count = (TextView) findViewById(R.id.player1Count);
        player2Count = (TextView) findViewById(R.id.player2Count);





        btnGreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Green){
               count1 = Integer.parseInt(player1Count.getText().toString());
               count1++;
              player1Count.setText(count1);
            }
        }});

    }

谁能告诉我发生了什么事?它应该相当简单:每个视图都在java代码中标识,然后当单击绿色按钮时,如果布尔“绿色”为真(我将其设置为进行测试),它将从textview获取字符串(从“0”开始),将其转换为int,然后向其中添加一个并相应地更改textview。但是每次都会崩溃。任何人都知道它为什么不起作用?

1 个答案:

答案 0 :(得分:0)

而不是:

  player1Count.setText(count1);

做的:

  player1Count.setText(String.valueOf(count1));

问题在于,如果将整数传递给setText(),它将理解为' String资源ID)..而不是变量的值。

它基本上是在思考'你想使用这种方法:http://developer.android.com/reference/android/widget/TextView.html#setText(int)

而不是这个:  http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)