search

Home  >  Q&A  >  body text

android - 我能否实现一个不需主动传入上下文的dialog?

既然我可以通过注册activity生命周期回调的方法在任意地方获取到最后一个onresume的activity,
那么我是否可以创建一个工具类,工具类利用这个activity来构造dialog呢?
这样做有什么坏处呢?
我现在用一个toast工具类,在工具类中直接使用了application的context,这样做可以吗?

阿神阿神2885 days ago639

reply all(6)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 09:18:44

    Yes, you can, but why? Just encapsulate a dialog tool class and pass the activity. As for toast, using applicationContext is a good idea.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:18:44

    Just construct the Dialog and directly pass the Activity context to it. You don’t need to bother with callbacks or anything like that. You can refer to other people's packaged tool libraries to see other people's ideas.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:18:44

    Just be smart, you can use an activity as a dialog, just set its theme to dialog, as the official website says

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:18:44

    Originally, the system-level dialog is very convenient. You only need to pass in the applicationContext to implement a pop-up box. However, due to excessive customization by various manufacturers (I encountered Xiaomi’s system-level pop-up box customization is disgusting, the same version, update Modify once after implementation), so it is best to use an activity in a customized dialog format as a pop-up box to implement all the above. Many companies currently do this, such as tencent’s carrier pigeon push, which can ensure Launch successfully without the hassle of customization.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:18:44

    Android Dialog, you have to pass the Context no matter what. Passing Activity is actually equivalent to passing Context. It is not possible to use Application's Context; furthermore, static Context is not recommended and may cause memory leaks.

    However, you can hide or simplify this process through methods such as dependency injection.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:18:44

    You can’t (although I want to say I don’t recommend it)
    Building you have already implemented it, let’s guess what will happen.

    1. The network request was sent, and then the page was ended, but the request was not canceled. When the request returned, a dialog box popped up. How to explain this Dialog? If this Dialog has subsequent operations and the operations have data, where should these processing codes be placed? ?Alright, you successfully put these data in the Dialog instance and created a new internal class. Congratulations, the memory of the Activity that was just ended is leaked

    2. How to restrict people from using a universal Dialog? It can be played anywhere and the code structure can be maintained?

    3. For a small project, you can directly create a BaseActivity according to your needs, handle the code structure and pop up a dialog box without much trouble. The reason is not sufficient.

    reply
    0
  • Cancelreply