How long can a UI-related object stay usable?
I guess this is a lame question, I can't even make up a proper subject! Here is what I'm trying to do under Android:
public void onCreate(Bundle savedInstance) {
...
AskFilename ask = new AskFilename();
...
}
Here, AskFilename
class will present a user interface to let the user enter a filename. However, the ask
object will be out of scope once the onCreate()
method returns. So this means there will be no reference to ask
any more (assuming inside AskFilename
class, I did not assign its this
pointer to any other variable), and so GC will, sooner or later, "collect" it. When this happens, if the user hasn't OK'ed the dialog box, the code in AskFilename
is already unavailable and开发者_如何学C therefore the system will crash. Is my understanding correct?
(I can't think of a way to experiement with this idea, because I don't know how to make GC do its job. It seems that GC kicks in only when it wants to! Is there a way to make it do its job?)
If the above is correct, then what is the proper way to new a UI-related object? I know I can make evrything inside AskFilename
static, or I can make ask
a static vairable and assign it to null when it's done. But is there any other way? Or, the idea itself is bad in the first place?
(Does it make any difference if AskFilename is an "inner" class of the Activity? Like MyActivite.AskFilename.)
Thank you in advance.
Firstly, you can just put the declaration AskFilename ask;
outside of the method declaration, i.e. as a member of your class. Then you initialise it with ask = new AskFilename();
in your onCreate method.
However, the thing to know is that your constructor probably won't look like that. Every Android UI component contains a callback (a reference) to the thing containing it. You typically do this by passing a Context
to the constructor of a UI component- inside an Activity, the context is usually just the Activity itself, so you just use the this
keyword. e.g:
TextView tv = new TextView(this);
However you construct your AskFilename dialog, I expect you will need to pass the Context down to its components. So your constructor will probably need to take a Context argument:
ask = new AskFilename(this);
Additionally, your Activity will hold references (implicitly) to all of its UI components, and dialogs it shows with onCreateDialog()
So your object won't get picked up by the GC.
It gets these references either when you call setContextView or make the dialog.
精彩评论