Java Variable Scope Global

时间:2016-10-08 17:03:54

标签: java android variables methods scope

我试图用简单的例子来理解变量范围。 我需要有关此代码的帮助

package com.varialescope.examplevariablescope;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Button buttonOne;
private Button buttonTwo;
private String mText = "Hello World";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Initialialize UI elements

    buttonOne = (Button) findViewById(R.id.button_one);
    buttonOne = (Button) findViewById(R.id.button_two);

    //Button One click listener

    buttonOne.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //Set new text

            mText = "ONE";

            Toast.makeText(MainActivity.this, mText,      Toast.LENGTH_SHORT).show();
        }
    });

    //Button Two click listener

    buttonTwo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
        }
    });
}
}

如何从点击侦听器方法访问mText字符串?

如何为mText设置一个新字符串,点击按钮One并使其可全局访问?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

anonymous创建clicklistener类对象任何anonymous类或内部类对象都有关于外部类对象的信息,然后它有权访问方法和变量外类对象