gpt4 book ai didi

java - Android:如何从类的方法访问值?

转载 作者:行者123 更新时间:2023-11-30 00:37:34 25 4
gpt4 key购买 nike

看,我有 2 个类可以说是登录类和欢迎类,在登录类中我有全局变量 String Email; 和一个 OnCreate() 。我在该方法中设置了电子邮件的值,现在我的问题是如何获取从方法初始化的变量的值?

public class LoginActivity extends AppCompatActivity {
private EditText email,password;

public String emailText;

protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

email = (EditText) findViewById(R.id.email);
//I want to get this value
emailText = email.getText().toString();
}
}

我的另一个类(class)是

public class Welcome extends Activity{
protected void onCreate(Bundle savedInstanceState) {
TextView textView = (TextView) findViewById(R.id.email);
//this is what I did which is the variable that was unInitialized
LoginActivity loginActivity = new LoginActivity();
textView.setText(loginActivity.getEmailText());
}
}

最佳答案

您必须以一些额外的方式开始欢迎 Activity :

    Intent startWelcomeActivityIntent = new Intent(context, Welcome.class);
startWelcomeActivityIntent.putExtra("keyForUsername", userNameString);
startWelcomeActivityIntent.putExtra("keyForPassword", passwordString);
startActivity(startWelcomeActivityIntent);

然后从 Welcome Activity 的 onCreate 方法中检索这个 extras:

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

Intent intentWithData = getIntent();
String userNameFromLoginActivity = intentWithData.getStringExtra("keyForUsername");
String passwordFromLoginActivity = intentWithData.getStringExtra("keyForPassword");
}

关于java - Android:如何从类的方法访问值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com