如何将变量从OnCreate传递给函数(视图)

时间:2019-04-14 19:03:34

标签: android

我有一个活动,该活动从另一个活动中获取变量,并且我想在用户单击按钮时显示此变量。 问题是SaveFile(View view)方法找不到“ SurveyTilte”变量。 如何传递此变量?

public class CreateSurvey extends AppCompatActivity {
    TextView Textfile;
    String SurveyTilte;
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_survey);
        Bundle extras = getIntent().getExtras();
        SurveyTilte = extras.getString("SurveyTilte");
}
}

我不能,但是OnClickListener中的代码是因为有@Override方法

public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(CreateSurvey.this, "Permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(CreateSurvey.this, "Permission not granted", Toast.LENGTH_SHORT).show();
                    finish();
                }
        }

3 个答案:

答案 0 :(得分:0)

String中删除String SurveyTilte = extras.getString("SurveyTilte");关键字,将值分配给类字段,而不是局部变量:

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_survey);
        Bundle extras = getIntent().getExtras();
        SurveyTilte = extras.getString("SurveyTilte");
}

然后

public void SaveFile(View view) {
  Textfile = (TextView) findViewById(R.id.surveyDetails);
  Textfile.setText(SurveyTilte); // <-- reference field that contains value from intent data
}

答案 1 :(得分:0)

这实际上是Java而不是android的问题。

这样做:

protected void onCreate(Bundle savedInstanceState) {
    ...
    String SurveyTilte = extras.getString("SurveyTilte");
}

您实际要做的是创建一个与您的类字段变量分开的局部变量,并使用相同的名称,并且该变量“有效”且可用于该特定方法范围。意味着退出onCreate方法时,您将失去其引用(因而失去其值)。

您需要做什么:

您要做的就是不要在onCreate内声明新变量,而要使用您在class属性中Advanced中声明的相同变量。

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    SurveyTilte = extras.getString("SurveyTilte");
}

这就是在整个类范围内对值使用相同引用的方式。

答案 2 :(得分:0)

我认为这可以为您提供帮助。

public class CreateSurvey extends AppCompatActivity {
 TextView Textfile;
 String SurveyTilte;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.create_survey);
     }
  }



public void SaveFile(View view) {
  Bundle extras = getIntent().getExtras();
  if(extras != null) {
    SurveyTilte = extras.getString("SurveyTilte");
    Textfile = (TextView) findViewById(R.id.surveyDetails);
    Textfile.setText(SurveyTilte);
  } 
}
相关问题