因此,我启动应用程序,并在 MainActivity 的 onCreate 方法中更改变量值。但是当我单击按钮时,我会进入另一个活动,在这个活动中我尝试获取更改后的变量,我只得到变量的原始值。
所以,我的问题是我不知道如何从第一堂课中获取更改后的变量。我怎么做?
这是代码:
主要活动:
package com.example.getandset;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
//Initialised variable
String tag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//The text that I want to show in the next class
setTag("Show this text");
}
public void setTag(String t){
tag =t;
}
public String getTag(){
return tag;
}
public void onClick_Start(View v){
//start of the next Class
startActivity(new Intent(this, CalledActivity.class));
}
}
和称为活动:
package com.example.getandset;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class CalledActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_called);
TextView tv = (TextView)findViewById(R.id.textView);
//trying to get the changed variable
tv.setText("Got text: "+ new MainActivity().getTag());
}
}