我编写了这个小应用程序,它运行得很好。但我对 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");
}
}
}
最佳答案
通过在任何方法之外但在类内部声明它们,使它们成为属于该类的变量:
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");
}
}
在方法(或任何用大括号括起来的语句 block ,如 {} )内声明的变量仅在该方法/ block 内具有作用域(即它们仅可见)。声明为类变量的变量可以被赋予公共(public)、私有(private)、 protected 或默认/包范围。将它们声明为公共(public),以便能够在任何其他类中访问它们。
关于java - 如何访问单独函数中的变量 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4979975/