变量没有在android

时间:2015-04-26 11:51:10

标签: android

我使用以下代码来增加变量flag1,flag2,flag3,flag4。
我想要的输出是:

  

... 1,2,3,4,5,6,7,8,9,10,11

我得到的输出是:

  

... 1,2,3,4,5,6,7,8,5,6,7,8,5,6

int flag = 0;
btnnxt = (Button) findViewById(R.id.btnnext);
        btnnxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final RadioButton ans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
                String anstext = ans.getText().toString();
                int flag1 = 1, flag2 = 2, flag3 = 3, flag4 = 4;
                if (anstext.equalsIgnoreCase(acar[flag])) {
                    correct++;
                }
                flag++;

                tvn.setText(aqr[flag]);
                if (flag <= aqr.length) {
                    if(flag!=1) {
                        flag1 += 4;
                        flag2 += 4;
                        flag3 += 4;
                        flag4 += 4;
                    }
                    Log.e("has",String.valueOf(flag1));
                    Log.e("has",String.valueOf(flag2));
                    Log.e("has",String.valueOf(flag3));
                    Log.e("has",String.valueOf(flag4));
                }
});

提前致谢!

1 个答案:

答案 0 :(得分:1)

问题在于变量声明变量int flag1 = 1, flag2 = 2, flag3 = 3, flag4 = 4必须在OnClickListener之前声明

int flag1 = 1, flag2 = 2, flag3 = 3, flag4 = 4;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        btnnxt = (Button) findViewById(R.id.btnnext);
        btnnxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final RadioButton ans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
                String anstext = ans.getText().toString();
                int flag1 = 1, flag2 = 2, flag3 = 3, flag4 = 4;
                if (anstext.equalsIgnoreCase(acar[flag])) {
                    correct++;
                }
                flag++;

                tvn.setText(aqr[flag]);
                if (flag <= aqr.length) {
                    if(flag!=1) {
                        flag1 += 4;
                        flag2 += 4;
                        flag3 += 4;
                        flag4 += 4;
                    }
                    Log.e("has",String.valueOf(flag1));
                    Log.e("has",String.valueOf(flag2));
                    Log.e("has",String.valueOf(flag3));
                    Log.e("has",String.valueOf(flag4));
                }
});
}