I have written this small app and it works perfectly. But I am new to java and assume there must be a better way to write this so that the variables can be read in both functions. Is there?
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");
}
}
}
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.
来源:https://stackoverflow.com/questions/4979975/how-to-access-variables-in-separate-functions-android