单击按钮时应用程序崩溃

时间:2014-03-30 16:45:11

标签: java android

我正在尝试构建自定义数字选择器,每次点击+或 - 按钮时我的应用都会崩溃。我没有在MainActivity.java中收到任何错误。 有人知道可能是什么情况吗? 这是代码:

public class MainActivity extends Activity {

    TextView tvHeight;
    int counter = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button heightMinus = (Button) findViewById(R.id.height_min);
        Button heightPlus = (Button) findViewById(R.id.height_plus);
        tvHeight = (TextView) findViewById(R.id.textViewHeight);

        heightPlus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                counter++;
                tvHeight.setText(counter);

            }
        });

        heightMinus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                counter--;
                tvHeight.setText(counter);

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

2 个答案:

答案 0 :(得分:3)

您需要调用期望CharSequence作为参数的setText方法。所以替换

tvHeight.setText(counter);

tvHeight.setText(String.valueOf(counter));

目前您正在调用setText(int resid),它将尝试查找您在strings.xml文件中定义的字符串资源ID。

所以我猜你的代码会抛出一个ResourceNotFoundException

答案 1 :(得分:3)

更改此

tvHeight.setText(counter);

tvHeight.setText(String.valueOf(counter));

查看方法

public final void setText (int resid)

这个

public final void setText (CharSequence text)

使用第一种方法Android会查找具有ID的资源,如果找不到,则会获得ResourceNotFoundException。有一个接受int是资源ID,另一个接受CharacterSequecne