如何在单独的函数中访问变量 - Android

时间:2011-02-12 19:00:58

标签: java android function variables shared

我写过这个小应用程序,它完美无缺。但我是java新手并且假设必须有更好的方法来编写它,以便可以在两个函数中读取变量。有吗?

package max.multiplebuttons.com;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class multibuttons extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView question = (TextView)findViewById(R.id.question);
        TextView textView = (TextView)findViewById(R.id.textView);
        Button answer1 = (Button)findViewById(R.id.answer1);
        Button answer2 = (Button)findViewById(R.id.answer2);
        answer1.setText("button1");
        answer2.setText("button2");
        question.setText("click a button");
        textView.setText("Some Text");
        answer1.setOnClickListener(this);
        answer2.setOnClickListener(this);
    }
    public void onClick(View v){
        TextView textView = (TextView)findViewById(R.id.textView);
        Button answer1 = (Button)findViewById(R.id.answer1);
        Button answer2 = (Button)findViewById(R.id.answer2);
        if(v==answer1){
            textView.setText("1");
        }
        if(v==answer2){
            textView.setText("2");
        }
    }
}

1 个答案:

答案 0 :(得分:7)

通过在任何方法之外但在类中声明它们来使它们成为属于该类的变量:

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

}

然后你只需要在onCreate方法中初始化它们:

public void onCreate(Bundle savedInstanceState) {

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

您不需要在onClick方法中再次初始化它们:

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

在方法内部声明的变量(或由大括号括起的任何语句块,如{})仅在该方法/块内具有范围(即它们仅可见)。声明为类变量的变量可以赋予public,private,protected或default / package范围。将它们声明为公共的,以便能够在任何其他类中访问它们。