如何在触摸屏关闭后禁用活动的新实现?

时间:2015-09-07 09:27:43

标签: android

如何在触摸屏关闭后禁用活动的新实现?

注意:设备未关闭,但触摸屏也已关闭。

例如,请参阅以下代码,当我们点击imageView对象时,随时将1单位增加到textView对象值。如果我们在imageView对象上单击十次,则textView对象将具有10值。现在如果我没有点击触摸屏,结果触摸屏将关闭。现在,当我想打开触摸屏时,textView对象值为0。虽然它应该具有相同的10值。

public class MainActivity extends Activity {

    ImageView imageView;
    Integer integer = 0;
    TextView textView;

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

        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText(integer.toString());
        imageView.setOnClickListener(new View.OnClickListener() {@Override
            public void onClick(View v) {
                integer = integer + 1;
                textView.setText(integer.toString());
            }
        });
    }

}

1 个答案:

答案 0 :(得分:1)

您必须使用onSaveInstanceState来保存您的状态

public class MainActivity extends Activity {

    ImageView imageView;
    Integer integer = 0;
    TextView textView;

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

        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        textView = (TextView) findViewById(R.id.textView);
        if (savedInstanceState!=null) {
             integer = savedInstanceState.getInt("count");
        }
        textView.setText(integer.toString());
        imageView.setOnClickListener(new View.OnClickListener() {@Override
            public void onClick(View v) {
                integer = integer + 1;
                textView.setText(integer.toString());
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("count", integer);
    }

}

http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState