繁体   English   中英

单击按钮时应用崩溃

[英]App crashes when clicking on a button

我正在尝试构建自定义号码选择器,每次单击+或-按钮,我的应用程序都会崩溃。 我在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;
    }
}

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

tvHeight.setText(counter);

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

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

所以我猜你的代码抛出了ResourceNotFoundException

改变这个

tvHeight.setText(counter);

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

看一下方法

public final void setText (int resid)

和这个

public final void setText (CharSequence text)

如果使用第一种方法,Android将寻找一个ID为参考的Resource(如果找不到),您将得到ResourceNotFoundException 有一个采用int的资源ID,另一个采用CharacterSequecne

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM