Android solves the problem that the back event of activity cannot be captured when dialog pops up

This article describes an example of how Android can not capture the back event of activity when dialog pops up. Share with you for your reference. The specific analysis is as follows:

In some cases, we need to capture the back key event, and then write the processing we need in the captured event. Generally, we can capture the back event in the following three ways:

1) Override onkeydown or onkeyup methods

2) Override onbackpressed method

3) Override dispatchkeyevent method

What is the difference between these three methods is not described here. Interested friends can refer to relevant materials.

However, if you want to capture the back key event when a dialog pops up, none of the above three methods can be implemented. Because the above methods are rewritten in the activity, that is, when the activity is the current focus, it can capture the corresponding back key event. When a dialog pops up, the dialog obtains the current focus. Therefore, the methods in the activity cannot obtain the back key event. There are two ideas:

1) Set setoncancellistener listening of dialog:

In this way, you can capture the event of the back key. When you press the back key, the default operation of the system will cause the dialog to cancel. At this time, oncancellistener will be triggered, and then you can implement the operation you want in the OnCancel method.

2) Set the setonkeylistener of dialog and override the dispatchkeyevent method

Then, you can implement the operations you want in the dispatchkeyevent.

I hope this article will be helpful to your Android program design.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>