[英]How to use layout components in functions which are out of activities and fragments in Android?
I have a layout and I want to use its component in a function.我有一个布局,我想在 function 中使用它的组件。 How can I do that?
我怎样才能做到这一点?
This is the XML:这是 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textview.MaterialTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/title"
android:layout_gravity="center"
android:textColor="#0055FF"
android:textSize="30dp"/>
</LinearLayout>
And this is the function:这是 function:
fun Context.Dialog(){
title.setOnItemClickListener{
Toast.makeText(this,"OK",Toast.LENGTH_LONG).show()
}
}
But title is not recognized in the Dialog function.但在对话框function 中无法识别标题。 I don't want to use Dialog function in an activity or a fragment.
我不想在活动或片段中使用Dialog function。
I wouldn't move initialization of OnCLickListener
out of activity or fragment, because there (in activity or fragment) you have access to all views defined in the layout.我不会将
OnCLickListener
的初始化移出活动或片段,因为在那里(在活动或片段中)您可以访问布局中定义的所有视图。 But if you want to create a separate function out of activity or fragment you need to pass either views or activity or fragment as parameters:但是,如果您想在活动或片段之外创建单独的 function,则需要将视图或活动或片段作为参数传递:
// passing views
fun showDialog(title: View) {
title.setOnClickListener { Toast.makeText(title.context, "OK", Toast.LENGTH_LONG).show() }
}
// passing activity
fun showDialog(activity: Activity) {
val title: View = activity.findViewById(R.id.title);
title.setOnClickListener { Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show() }
}
// passing fragment
fun showDialog(fragment: Fragment) {
val title: View? = fragment.view?.findViewById(R.id.title);
title?.setOnClickListener { Toast.makeText(fragment.context, "OK", Toast.LENGTH_LONG).show() }
}
Also you can create an extension function on View
:您也可以在
View
上创建扩展 function :
fun View.showDialogWhenClick() {
setOnClickListener { Toast.makeText(context, "OK", Toast.LENGTH_LONG).show() }
}
And use it in Activity or Fragment like this:并像这样在 Activity 或 Fragment 中使用它:
title.showDialogWhenClick()
First you need to get the reference to title first.首先,您需要先获取对标题的引用。 Then set listeners and such.
然后设置监听器等。
in your activity在你的活动中
fun onCreate(savedInstanceState:Bundle){
setContentView(R.layout.activity_layout)
Context.Dialog(this);
}
in your Context.Dialog:在您的 Context.Dialog 中:
fun Context.Dialog(activity:Activity){
var title = activity.findViewById(R.id.title);
title?.setOnItemClickListener{
Toast.makeText(this,"OK",Toast.LENGTH_LONG).show()
}
}
or something like that或类似的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.