无法使用FindViewById访问自定义视图



我已经写了一个小型包装器,以抽象一些实现详细信息,并添加一些我们自己的业务逻辑。此包装器的签名看起来像:

public class BFPlayer extends PlayerView {

现在,我使用此视图有一项活动,我希望通过编程方式访问视图,以便在其上调用方法。这是我当前的代码:

public class PlayBroadcastActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_broadcast);
        BFPlayer player = findViewById(R.id.player);
        player.displayMessage("Test");
    }
}

和此活动的XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PlayBroadcastActivity">
    <com.blueframetech.bfplayer.BFPlayer
        android:id="@+id/player"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

这引发了错误:

> Task :app:compileDebugJavaWithJavac FAILED
/Users/stevenbarnett/Source/BluePlayer/AndroidSDK/app/src/main/java/com/blueframetech/blueframesdk/PlayBroadcastActivity.java:16: error: cannot access PlayerView
        BFPlayer player = findViewById(R.id.player);
                          ^
  class file for com.google.android.exoplayer2.ui.PlayerView not found
1 error

为什么会发生这种情况?错误引用com.google.android.exoplayer2.ui.PlayerView,但我正在尝试访问PlayerView子类。为什么要访问这个第三方依赖的库?另外,为什么尝试失败?

对于Java/Kotlin代码要使用类,编译器需要访问继承层次结构中的所有类,因此它可以访问public成员的完整范围。由于BFPlayer扩展了PlayerView,因此BFPlayer的消费者需要访问PlayerView

但是,在包含 BFPlayer的模块中,您使用implementation集成了超层次。这说明"使用此模块的这种依赖关系,但不要将其标记为任何依赖此模块的任何其他模块的传递依赖性"。对于应用模块,implementation很好,因为没有其他模块取决于应用模块。

但是,BFPlayer在库模块中。因此,implementation防止依赖BFPlayer模块的模块具有访问范围。

99.44%的时间,在库模块中,您希望主要依赖关系使用api而不是implementation,因此库模块的消费者还可以吸引其他(传递(依赖项。

因此,将implementation更改为api中的CC_17,用于epoplayer依赖项(大概是任何其他模块(,您应该能够克服问题。

最新更新