[英]Example on transferring variable values between android activities
我在類“ first”中有兩個變量,我希望在“第二”類中使用這些值來完成某些任務。 什么是最簡單的方法。 在我進行android開發時,2個變量值是用戶輸入的edittext值
您可以將它們放在第二類的constructor
或將它們public static
以便使用類名可以訪問它們。
使用靜態,它將被所有線程共享。 最好私有化並提供getter和setter方法,因此您可以通過getter方法訪問值。
在first
堂課中,您可以做這樣的事情,
name_text = (EditText) findViewById(R.id.nameText);
String name = name_text.getText().toString();
Intent intent = new Intent(first.this, Second.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("name",name);
startActivity(intent);
在Second
班,你可以做這樣的事情,
Intent i = this.getIntent();
String name = i.getStringExtra("name");
如果您的意思是“第一和第二是活動”,則可以使用putExtra概念。
FirstActivity.java
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("var1", editText1.getText().toString());
intent.putExtra("var2", editText2.getText().toString());
startActivity(intent);
SecondActivity.java
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String txtOne = bundle.getString("var1");
String txtTwo = bundle.getString("var2");
}
當您使用Intent
從Activity1
導航到Activity2
,請使用Intent.putExtra("key", "Value")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.