簡體   English   中英

Android中的activity和fragment之外的函數如何使用布局組件?

[英]How to use layout components in functions which are out of activities and fragments in Android?

我有一個布局,我想在 function 中使用它的組件。 我怎樣才能做到這一點?

這是 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>

這是 function:

fun Context.Dialog(){
    title.setOnItemClickListener{
        Toast.makeText(this,"OK",Toast.LENGTH_LONG).show()
    }
}

但在對話框function 中無法識別標題 我不想在活動或片段中使用Dialog function。

我不會將OnCLickListener的初始化移出活動或片段,因為在那里(在活動或片段中)您可以訪問布局中定義的所有視圖。 但是,如果您想在活動或片段之外創建單獨的 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() }
}

您也可以在View上創建擴展 function :

fun View.showDialogWhenClick() {
    setOnClickListener { Toast.makeText(context, "OK", Toast.LENGTH_LONG).show() }
}

並像這樣在 Activity 或 Fragment 中使用它:

title.showDialogWhenClick()

首先,您需要先獲取對標題的引用。 然后設置監聽器等。

在你的活動中

fun onCreate(savedInstanceState:Bundle){
setContentView(R.layout.activity_layout)
Context.Dialog(this);
}

在您的 Context.Dialog 中:

fun Context.Dialog(activity:Activity){
    var title = activity.findViewById(R.id.title);
    title?.setOnItemClickListener{
        Toast.makeText(this,"OK",Toast.LENGTH_LONG).show()
    }
}

或類似的東西

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM