Android在OnCreate之前声明变量?

时间:2014-09-02 22:26:21

标签: android variables scope textwatcher

是否可以在Android中的onCreate()方法之前创建变量?我过去曾尝试这样做,但没有用,所以我假设你不能,但我只想仔细检查。原因是因为我试图访问我TextWatcher中作为计数器的变量,但是它超出范围并要求我将其作为最终,这显然不起作用,因为它作为一个计数器和需要增加。我在下面附上了我的代码:

int counter = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText answerText = (EditText) findViewById(R.id.answer);
    final TextView text = (TextView) findViewById(R.id.wordtoanswer);
     final ArrayList updatedList = helperMethod();
     text.setText(updatedList.get(0).toString());
     final String wordFinal = updatedList.get(0).toString();

     while(true)
     {
    answerText.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // TODO Auto-generated method stub
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // TODO Auto-generated method stub
        }

        public void afterTextChanged(Editable s) {
            System.out.println(counter);
            String answer = s.toString();
            if(answer.equals(wordFinal))
            {   
                text.setText(updatedList.get(counter).toString());
                answerText.setText("");
            }
        }
    });
    counter++;
}
}

希望你们理解我为什么要在onCreate()之前声明它,因为只有这样,TextWatcher内的方法才能实际访问它而不会超出范围。无论如何我可以解决这个问题吗?如果您需要更多信息/代码,请告诉我们!

1 个答案:

答案 0 :(得分:2)

将引用声明为成员变量:

private TextView text;

在OnCreate方法中实例化它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.wordtoanswer);
    //...
}