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

标签 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");
        }
    }
}

最佳答案

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

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/

相关文章:

java - 在 DispatcherServlet 中未找到名称为 'SpringDispatcher' 的 URI 的 HTTP 请求映射

android - 找不到带有 Dagger 2 的符号 ViewModel

Android studio aar 文件报错类未找到

python - 为什么我可以在函数中使用变量之前在 Python 中定义它?

在不声明函数指针的情况下将 void* 作为函数调用

java - 从 JAX-RS 服务获取资源时出错

java - JEdi​​torPane 中的文本格式设置

android - 需要均匀间隔的按钮行

java - 如何在 Java 程序中使用 Python 类?

java - 'Conditional expressions can be only boolean, not integral.' 是什么意思?