当我尝试旋转屏幕时,它不会删除数据,但是当我离开活动并返回时,计数器值会回到0。
我已经设置了保存数据的方法,但它仍然没有保存。这是为什么?
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add = 0;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Counter = savedInstanceState.getInt("Count");
add = savedInstanceState.getInt("Add");
}
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Counter = ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
finish();
}
});
handler.postDelayed(new Runnable() {
@Override
public void run() {
Counter = AutoCounter(Counter, add);
Display(Counter, myTextView);
handler.postDelayed(this, 100);
}
}, 10);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("Count", Counter);
savedInstanceState.putInt("Add", add);
super.onSaveInstanceState(savedInstanceState);
}
public int ButtonCounter(int Counter) {
Counter += 1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter += add;
return Counter;
}
public void Display(int Counter, TextView myTextView) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
}
答案 0 :(得分:0)
我的代码就是这样......
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("Count", Counter);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
{
if (savedInstanceState.containsKey("Count"))
{
Counter = savedInstanceState.getInt("Count");
}
}
}
不同之处在于我没有创建最终的Bundle而且我在super.onSave之后保存它..这看起来很奇怪....