简体   繁体   English

如何将动态字符串声明为public?

[英]How would I declare a dynamic string as public?

I've created a setOnFocusChangeListener on an EditText so it will grab the string and add it to a TextView via setText() . 我已经在EditText上创建了setOnFocusChangeListener ,因此它将抓取字符串并将其通过setText()添加到TextView However, I need a way to publicly and dynamically (in case they change the EditText again) use the toString() method so I can use it in another setOnFocusListener . 但是,我需要一种公开动态地(如果他们再次更改EditText )使用toString()方法的方法,以便可以在另一个setOnFocusListener使用它。

Heres my code, perhaps it will explain things in a less confusing way: 这是我的代码,也许它将以一种不太混乱的方式解释事情:

final TextView team1NameScore = (TextView) findViewById(R.id.team1NameScore);
final EditText team1Name = (EditText) findViewById(R.id.team1Name);

team1Name.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            String team1NameString = team1Name.getText().toString();
            // Right here I need to make the above line public so I can use it later!
            if (!hasFocus) {
                team1NameScore.setText(team1NameString + "'s Score:");
            }
        }
    });

(Read the comment on the 5th line) (阅读第五行的评论)

I have many focus listeners... I'd like to combine them into one preview that I generate for the user at the end (using `setText(textview1 + textview2 + team1Name) 我有很多焦点侦听器...我想将它们合并为一个最终为用户生成的预览(使用`setText(textview1 + textview2 + team1Name)

Declare the string as an instance variable at the top of your class. 在类的顶部将字符串声明为实例变量。

It cannot be a variable local to your parent method for the anonymous inner class, as then it would have to be final to be accessed by the listener, which means you can't alter its value. 对于匿名内部类,它不能是父方法本地的变量,因为它必须是final才能被侦听器访问,这意味着您不能更改其值。 However, if you declare it as a global instance variable, your listener can access it, as can any other methods and listeners in your class. 但是,如果将其声明为全局实例变量,则您的侦听器可以访问它,您的类中的任何其他方法和侦听器也可以访问它。

Simply create a field variable: 只需创建一个字段变量:

public class Example extends Activity {
    public String team1NameString = "";

Then use it like any other variable: 然后像其他变量一样使用它:

public void onFocusChange(View v, boolean hasFocus) {
    team1NameString = team1Name.getText().toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM