Расширения Kotlin для Android: как получить ссылку на представление в макете, которое включено в другой макет?
У меня есть макет, который включает в себя другой макет:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<include layout="@layout/included_layout" />
</LinearLayout>
included_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/includedTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Included TextView"/>
</LinearLayout>
Как я могу получить ссылку на TextView во включенном макете? Это не поддерживается (пока)?
Основная деятельность:
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.activity_main.*
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView.text = "text" // works!
textViewInclude.text = "textInclude" // does not work: "Unresolved reference: textViewInclude "
}
}
1 ответ
Решение
Вам следует import
включенный макет.
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.included_layout.* // Here
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// From activity_main.textView
textView.text = "text"
// From included_layout.textViewInclude
textViewInclude.text = "textInclude"
}
}
В Activity, где вы хотите получить доступ к другому элементу макета, щелкните Listner
class LoginActivity : AppCompatActivity(), View.OnClickListener {
override fun onClick(view: View?) {
when (view?.id) {
R.id.dialog_cancel-> { dialog.cancel() }
}
}
}
в другом макете, который вы импортируете в свой Activity, поместите onClick() в элемент и свяжите его с Activity, в которое вы импортировали onClick listner android:onClick="onClick"
Он будет работать определенно, и другой элемент xml будет прослушивать щелчок