SetContentViewを使用して設定した後、アクティビティはどのようにしてビューのインスタンスにアクセスできますか?アクティビティがロジックを含むカスタムビューを使用し、アクティビティがビューに設定する必要があるカスタムイベントリスナーを介してイベントをアクティビティに送信するには、このビューが必要なため、これが必要です。
kotlinのandroidstudioでプログラミングしています。以前はアクティビティにすべてのUIコントロールロジックが含まれていたので問題ありませんでしたが、カスタムビューでいくつかのUIコードを因数分解して、いくつかのアクティビティで再利用しています。
これがアクティビティの初期化です
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>
これがカスタムビュークラスCustomView.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
}
何かアイデアはありますか?
Kotlinでは、Kotlin合成を使用するのがより一般的です。
view_custom.setCustomViewListener(...)
注:リスナーの実装は、KotlinではなくJavaで記述したようです。インターフェイスはKotlinで定義されているため、次のようなものが必要です。
view_custom.setCustomViewListener(object : CustomView.MyCustomViewListener {
override fun onCancelled() {
...
}
})
個人的にはラムダを使用するのが好きです。残念ながら、ラムダをKotlinSAMインターフェースとして使用することはできません。ただし、インターフェイスの代わりにtypealiasを使用することもできます。
typealias MyCustomerViewListener = () -> Void
次に、代わりにこれを使用できます。
view_custom.setCustomViewListener {
// listener code
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加