首页 > 解决方案 > 无法从主项目访问变量?

问题描述

我无法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();
    }
}

标签: javaandroidkotlin

解决方案


hiContextAccessor接口添加属性:

interface ContextAccessor {

    val hi: String
    // ...
}

MyActivity实现getHi()方法中:

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

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

var extractedHi: String? = null

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

推荐阅读