简体   繁体   English

如何使用OnPause方法

[英]how to use OnPause method

How to change button text loaded from EditText while in onPause() method? 在onPause()方法中,如何更改从EditText加载的按钮文本?

For example 例如

@Override
public void onPause(){
    button.setText(text.getText().toString());
    super.onPause()
}

When I press the back button it does not change the button text 当我按下后退按钮时,它不会更改按钮文本

Leaving aside the question of why you want to do this in onPause() in the first place... 首先忽略了为什么要在onPause()中执行此操作的问题...

Normally, the state of your views would be saved in onSaveInstanceState(...) . 通常,您的视图状态将保存在onSaveInstanceState(...) But according to the docs , there are no guarantees about whether the call to onSaveInstanceState(...) will occur before or after the call to onPause() . 但是根据文档 ,不能保证对onSaveInstanceState(...)的调用是在对onPause()的调用之前还是之后进行。 If onSaveInstanceState(...) is called before onPause() , then any changes you make in onPause() will be lost. 如果在onPause()之前调用onSaveInstanceState(...) ,则您在onPause()所做的任何更改都将丢失。

Please read documentation - it describes Android activity flow with excellent diagrams. 请阅读文档 -它以出色的图表描述了Android活动流程。
onPause() is already existing method in Your activity, thus You will need to @Override it. onPause()是您的活动中已经存在的方法,因此您将需要@Override Unless You modified back button behavior - here is what happens: 除非您修改了后退按钮的行为,否则会发生以下情况:

  • onPause() is executed when You press back, and button text is replaced (assuming text and button are visible in this scope) - for such short time, You won't be able to notice (unless device is lagging, anyway) 按下时执行onPause(),并替换按钮文本(假定此范围内的文本和按钮可见)-在这么短的时间内,您将无法注意到(除非设备滞后)
  • onStop() is executed next, and Your application exits shortly after 接下来执行onStop(),并且您的应用程序会在之后不久退出

If You want to try and check that text is properly set - You might find it easier to write: 如果您想尝试检查文本是否设置正确,则可能会更容易编写:

@Override
public void onPause(){
    super.onPause();
    Log.d("Text's text:" + text.getText().toString()
          + "Button:" + button.getText().toString());

}

You will need to import android.util.Log . 您将需要导入android.util.Log
Notice also, that it is highly recommended ( here ) that You call super() as first thing when overriding Android default methods. 还要注意,强烈建议( here )在覆盖Android默认方法时首先调用super()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM