【问题标题】:Can't access variable from main project?无法从主项目访问变量?
【发布时间】: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();
    }
}

【问题讨论】:

  • ApplicationMyActivity.ContextAccessor的代码是什么?我不明白这些东西是如何联系在一起的。
  • @al3c 好吧,我只是按照这个答案的建议:stackoverflow.com/a/63206457/13976983 他没有回答,所以我决定在这里问一个问题。
  • 如果您能启发我,我将不胜感激。因为我迷路了。我也看不出它们是如何联系在一起的:(
  • getApplicationContext 返回一个应用程序。我不知道应用程序是什么样的,您没有发布源代码。你希望它有一个名为hi 的属性我看到一个活动有一个hi public 归档,但它与任何东西都没有关系,它应该是一个名为getHi 的getter,并且至少是某个接口的一部分.
  • @al3c 我想我差不多明白了。但是,拜托,因为我是初学者,你能用代码写一个完整的答案吗?谢谢

标签: java android kotlin


【解决方案1】:

ContextAccessor接口中添加hi属性:

interface ContextAccessor {

    val hi: String
    // ...
}

并在MyActivity 中实现getHi() 方法:

@NotNull
@Override
public String getHi() {
    return hi;
}

在您的库类SomeLibraryClass 中,您可以像下面这样访问它:

var extractedHi: String? = null

fun someOtherMethod() {
    extractedHi = mContextAccessor?.hi
}

【讨论】:

  • 好的,但我遇到了同样的问题i.imgur.com/8Z6hjlR.png
  • 试试nonNullContext.hi,因为这是一个属性
  • 嗯,你应该这样做:mContextAccessor?.hi
猜你喜欢
  • 2015-12-07
  • 1970-01-01
  • 2022-07-19
  • 2013-09-22
  • 1970-01-01
  • 2015-09-25
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多