Android activity 如何访问当前视图的实例?

How can an Android activity access the instance if its current View?

在使用 SetContentView 设置视图实例后,activity 如何访问视图实例?我需要这个,因为 activity 使用一个包含逻辑的自定义视图,我需要这个视图通过 activity 需要在查看。

我正在使用 android studio in kotlin 进行编程。 我以前在 activity 中拥有所有 UI 控制逻辑,所以我很好,但我在自定义视图中分解了一些 UI 代码,以便在多个活动中重新使用它。

下面是activity

的初始化
class MyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.custom_view)

        // Here need to access the view instance
        *xxxxxxx*.setCustomViewListener(new CustomView.MyCustomViewListener() {
            @Override
            public void onCancelled() {
                // Code to handle cancellation from the view controls
            }
        });)
    }
}

这是视图布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button android:id="@+id/button_do"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Do" />

    <com.kotlin.app.views.CustomView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/view_custom" />
</FrameLayout>

这里是自定义视图classCustomView.kt

class CustomView : FrameLayout, View.OnClickListener {

    constructor(context: Context) : super(context)

    init {
    }

    interface CustomViewListener {
        fun onCancelled()
    }
    private var listener: CustomViewListener? = null

    fun setCustomViewListener(listener: CustomerViewListener) {
        this.listener = listener
    }

有什么想法吗?

How can an activity access the instance of the view, after it's been set using SetContentView?

第 1 步:将 android:id 属性添加到根 <FrameLayout> 元素。

第 2 步:在 activity 的 onCreate() 中,在 setContentView() 调用之后,调用 findViewById() 以根据 ID 检索 FrameLayout您在步骤 #1 中分配的。

the activity uses a custom view which includes logic and I need this view to sent events to the activity, through a custom event listener that the activity needs to set in the view

您也可以只调用 findViewById() 并提供自定义视图的 ID (findViewById(R.id.custom_view))。

请注意,几乎所有关于 Android 应用程序开发的书籍都涵盖了这一点。

在Kotlin中,更常见的是使用Kotlin synthetic:

view_custom.setCustomViewListener(...)

注意:您似乎是在 Java 而不是 Kotlin 中编写了侦听器实现。由于您的界面是在 Kotlin 中定义的,因此您需要这样的东西:

view_custom.setCustomViewListener(object : CustomView.MyCustomViewListener {
    override fun onCancelled() {
        ...
    }
})

Kotlin 中的 SAM 接口

我个人喜欢使用 lambda。遗憾的是,您不能将 lambda 用作 Kotlin SAM 接口。但是,您可以使用类型别名而不是接口:

typealias MyCustomerViewListener = () -> Void

那么你可以改用这个:

view_custom.setCustomViewListener {
    // listener code
}