首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么函数"if (counter >10)“不能工作?

为什么函数"if (counter >10)“不能工作?
EN

Stack Overflow用户
提问于 2019-02-06 21:46:20
回答 1查看 60关注 0票数 1

如果我的计数器大于10,我会尝试让AlertDialog出现。

我曾尝试在if语句中使用TextView变量peopleCount,但也不起作用。我知道使用TextView是行不通的,但我需要知道是否有解决办法。

代码语言:javascript
复制
private TextView peopleCount;
private ImageView plusOne;
private ImageView minusOne;
private ImageView reset;
private int counter;

private View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.ivPlusOne :
                plusCounter();
                break;
            case R.id.ivMinusOne :
                minusCounter();
                break;
            case R.id.ivReset :
                initCounter();
                break;

        }

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_people);

    peopleCount = (TextView)findViewById(R.id.tvPeopleCount);

    plusOne = (ImageView)findViewById(R.id.ivPlusOne);
    plusOne.setOnClickListener(clickListener);

    minusOne = (ImageView)findViewById(R.id.ivMinusOne);
    minusOne.setOnClickListener(clickListener);

    reset = (ImageView)findViewById(R.id.ivReset);
    reset.setOnClickListener(clickListener);

    initCounter();

    if( counter > 10) {
        AlertDialog.Builder peopleAlert = new AlertDialog.Builder(PeopleActivity.this);

        peopleAlert.setCancelable(false);
        peopleAlert.setTitle("People Count High");
        peopleAlert.setMessage("Please check and replenish inventory");

        peopleAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogPeople, int which) {
                dialogPeople.cancel();


            }

        });
        peopleAlert.show();
    }

private void initCounter(){
    counter = 0;
    peopleCount.setText(counter + "");
}
private void plusCounter(){
    counter++;
    peopleCount.setText(counter + "");
}
private void minusCounter(){
    counter--;
    peopleCount.setText(counter + "");
}

我原以为AlertDialog会在计数器达到11时出现,但什么也没发生。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-06 21:49:14

OnCreate只运行一次,您需要将if语句移到一个函数中,并从plusCounter()和minusCounter()函数中调用它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54555115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档