我是android中的一個begginer。我有一個簡單的代碼,我從第一個活動中調用一個活動,在第二個活動中,我有一個按鈕,其中第二個活動已完成,第一個活動出現。有沒有辦法在第一個activity中調用onCreate方法,因爲onCreate方法在第一個activity中永遠不會調用(onResume總是被調用)?我有沒有在清單文件中編輯一些東西?如何在完成第二個活動(被第一個活動稱爲)後在第一個活動中調用onCreate方法
以下是我的代碼
public class Activity1 extends Activity {
/** Called when the activity is first created. */
TextView mTextView ;
Button b1;
static int count=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textView2);
if (savedInstanceState == null) {
mTextView.setText("Welcome to HelloAndroid!");
} else {
mTextView.setText("Welcome Back!");
System.out.println("count------>"+ count);
}
final Intent i = new Intent(this,activity2.class);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(i);
}
});
}
@Override
public void onResume()
{
super.onResume();
System.out.println("inside Resume");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
count++;
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
System.out.println("MyBoolean"+ myBoolean);
System.out.println("myDouble"+ myDouble);
}
}
,這裏是我的第二個活動是由第一次叫activiy
public class activity2 extends Activity{
TextView textview;
Button b1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
textview = (TextView) findViewById(R.id.textView1);
textview.setText("in activity2");
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
有人請幫我 謝謝!
,嘿,你是正確的...感謝名單!但是當我這樣做onSaveInstanceState沒有執行。所以我從第一個活動中刪除了「finish()」,並執行了onSaveInstanceState。但onCreate alwyas中的「savedInstanceState」仍然爲空。我希望「savedInstanceState」在從第二個活動回來時不應該爲空。請您幫助我嗎? –
@ user1491193您是否看到我的編輯?如果您只想設置textview的文本...? – hasanghaforian
@ hasanghaforian:我只是不想顯示文本(「歡迎回來!」)。我想使用那個savedInstanceState。你能幫我嗎? –