How to access variables in separate functions - Android

不想你离开。 提交于 2019-12-02 12:12:39

Make them variables that belong to the class by declaring them outside of any method but inside the class:

public class multibuttons extends Activity implements OnClickListener {
TextView question;
TextView textview;
//etc.

}

Then you just need to initialise them inside the onCreate method:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    question = (TextView)findViewById(R.id.question);
    textView = (TextView)findViewById(R.id.textView);
    //...

You don't need to initialise them again at all in the onClick method:

public void onClick(View v){
    if(v==answer1){
        textView.setText("1");
    }
    if(v==answer2){
        textView.setText("2");
    }
}

Variables declared inside a method (or any block of statements enclosed by braces like {} ) only have scope (i.e. they are only visible) inside that method/block. Variables declared as class variables can be given public, private, protected or default/package scope. Declare them as public to be able to access them in any other class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!