【发布时间】:2020-11-30 06:53:10
【问题描述】:
我无法从我的库类中访问 hi 变量。为什么?看看吧:
我的库中有这个接口:
interface ContextAccessor {
fun getApplicationContext(): Application?
}
还有这段代码:
class SomeLibraryClass {
private var mContextAccessor: ContextAccessor?
String extractedHi = null
fun setContextAccessor(contextAccessor: ContextAccessor?) {
mContextAccessor = contextAccessor
}
fun someOtherMethod() {
mContextAccessor?.getAppContext()?.let { nonNullContext ->
// use nonNullContext here
extractedHi = nonNullContext.hi; // i get error here!
}
}
}
还有我项目中的这个类:
public class MyActivity extends Activity implements MyActivity.ContextAccessor {
private SomeLibraryClass someLibraryClassInstance = SomeLibraryClass();
public String hi = "hi";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ContextAccessor reference is set to some library class
someLibraryClassInstance.setContextAccessor(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Super important!
someLibraryClassInstance.setContextAccessor(null);
// OR create some method like `someLibraryClassInstance.removeContextAccessor(this)`
}
@Override
public Application getApplicationContext() {
return super.getApplication();
}
}
【问题讨论】:
-
Application和MyActivity.ContextAccessor的代码是什么?我不明白这些东西是如何联系在一起的。 -
@al3c 好吧,我只是按照这个答案的建议:stackoverflow.com/a/63206457/13976983 他没有回答,所以我决定在这里问一个问题。
-
如果您能启发我,我将不胜感激。因为我迷路了。我也看不出它们是如何联系在一起的:(
-
getApplicationContext返回一个应用程序。我不知道应用程序是什么样的,您没有发布源代码。你希望它有一个名为hi的属性我看到一个活动有一个hipublic 归档,但它与任何东西都没有关系,它应该是一个名为getHi的getter,并且至少是某个接口的一部分. -
@al3c 我想我差不多明白了。但是,拜托,因为我是初学者,你能用代码写一个完整的答案吗?谢谢