English 中文(简体)
与UI相关的对象可以使用多久?
原标题:How long can a UI-related object stay usable?
  • 时间:2011-02-10 20:46:15
  •  标签:
  • java
  • android

我想这是个蹩脚的问题,我连一个恰当的题目都编不出来!以下是我在安卓系统下尝试做的事情:

public void onCreate(Bundle savedInstance) {
    ...
    AskFilename ask = new AskFilename();
    ...
}

这里,AskFilename类将提供一个用户界面,让用户输入文件名。但是,一旦onCreate()方法返回,ask对象就会超出范围。因此,这意味着将不再引用ask(假设在AskFilename类内部,我没有将其this指针分配给任何其他变量),因此GC迟早会“收集”它。当这种情况发生时,如果用户没有确定对话框,AskFilename中的代码已经不可用,因此系统将崩溃。我的理解正确吗?

(我想不出一种方法来体验这个想法,因为我不知道如何让GC完成它的工作。似乎GC只有在它想做的时候才会加入!有办法让它完成它的任务吗?)

如果以上是正确的,那么新建UI相关对象的正确方法是什么?我知道我可以使AskFilename内部的每个值都是静态的,或者我可以使ask成为静态可用的,并在完成后将其分配为null。但是还有别的办法吗?或者,这个想法本身一开始就很糟糕?

(如果AskFilename是“活动”的“内部”类,会有什么不同吗?比如MyActivite.AskFilename。)

提前谢谢。

问题回答

首先,您可以只放入声明AskFilename ask在方法声明之外,即作为类的成员。然后用ask=new AskFilename()初始化它。

然而,需要知道的是,你的构造函数可能不会是那样的。每个Android UI组件都包含对包含它的东西的回调(引用)。您通常通过将Context传递给UI组件的构造函数来实现这一点-在Activity内部,上下文通常只是Activity本身,所以您只需使用this关键字。例如:

TextView电视=新的TextView(这个)

无论您如何构建AskFilename对话框,我预计您都需要将上下文传递给其组件。因此,您的构造函数可能需要使用Context参数:

 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.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...