在不扩展 Android 中 Activity 的类中使用 findviewbyid
我有一个当前正在扩展 Activity 的类,并且有 findViewById、ArrayAdapter 等方法。 我想把它变成一个独立的类,但以上所有方法都变得未定义。问题是什么?导入类还不够吗?例如,我为 findViewById 导入 android.view.View 但它仍然没有区别。 请指教。
I have a class that is currently extending Activity and I have methods like findViewById, ArrayAdapter etc.
I want to turn it into an independent class but all the above methods become undefined. What is the problem? Shouldn't importing the classes be enough? For eg, I import android.view.View for findViewById but it still makes no difference.
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该将 Activity 的实例传递给构造函数上的第二个类,如下所示:
在您的
Activity
中,像这样实例化您的类:在您的第二个类中,构造函数 将像这样:
然后当你想使用 findViewById() 方法时,你可以这样做:
you should pass the instance of your Activity to your Second Class on the constructor like this :
In your
Activity
Instanciate your Class like this :And in your second Class , the constructor will be like this :
and then when you want to use the
findViewById()
method , you can do like this :如果您想调用属于
Activity
的任何函数,那么您唯一需要的是Activity
的上下文。例如。
这里是B类。
if you want to call any function that belongs to
Activity
then only thing you need to have is context of theActivity
.eg.
Here is class B.
findViewById 是
Activity< 的非静态公共方法/code> 类,因此它只能用于
Activity
对象。因此,导入 android.view.View 和 android.app.Activity 不会使其可用。为了使其可用,您可以传递一个Activity
对象 - 通常是活动中的一个this
点。但是,请注意,您应该始终在 UI 线程中更新视图。findViewById is non-static public method of the
Activity
Class ,so it only be available for aActivity
object. Therefore, importandroid.view.View
andandroid.app.Activity
won't make it available. To make it available, you could pass around aActvity
object - usually athis
point in your activity. However, notice that you should always update your View in the UI thread.请尝试以下操作:
Please try the following: