如何正确地从私有类中调用函数?

huangapple go评论75阅读模式
英文:

How to properly call a function from a private class?

问题

我有一个关于从另一个类调用函数的问题。

class MyActivity: AppCompatActivity()
{
   override fun onCreate(savedInstanceState: Bundle?)
   {...}
   fun myFunction()
   {...}
   private class myAdapter (...) : BaseAdapter(), ListAdapter {
      ...
      //一些代码
      ...
      myFunction(); // <- 我应该如何正确调用它?
   }
}

因为我遇到了这个错误:
java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()'

我尝试调用 MainActivity().myFunction() 但结果一样。

英文:

I have an issue with calling a function from another class.

class MyActivity: AppCompatActivity()
{
   override fun onCreate(savedInstanceState: Bundle?)
   {...}
   fun myFunction()
   {...}
   private class myAdapter (...) : BaseAdapter(), ListAdapter {
      ...
      //some code
      ...
      myFunction(); // <- How should I call it properly?
   }
}

Because I'm getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

I tried calling it MainActivity().myFunction() but it does the same.

答案1

得分: 1

你的适配器应该是一个内部类。否则,它无法访问MainActivity的属性。
应该像这样:内部类myAdapter(...)

这可以解决你的问题,但不要采用这种方法,因为它违反了干净的代码和开闭原则。

英文:

Your adapter should be an inner class. Otherwise, it can not access the properties of MainActivity.
It should be like this: inner class myAdapter (...)

It can solve your problem but do not implement this approach as it's against clean code and the open-closed principle.

答案2

得分: 0

(context as MyActivity).myFunction()

实际上,我找到了我正在寻找的东西。我需要这样调用它:

英文:

Actually, I found what I was looking for. I need to call it like that:

(context as MyActivity).myFunction()

huangapple
  • 本文由 发表于 2023年5月28日 16:51:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定