簡體   English   中英

從 kotlin 中的另一個 class 文件訪問 textview

[英]Access a textview from another class file in kotlin

I create a textView with id ReceivedCodeTxt in activity_receive_code.xml file and then i create a new kotlin file with name SMSReceiver.kt ... Now i want to set text for a textView in my SMSReceiver.kt file but i dont know how to access它並從另一個 class 更改文本。

    val bundle = intent!!.extras
    try {
        if (bundle != null) {
            val pdusObj = bundle["pdus"] as Array<*>?
            for (i in pdusObj!!.indices) {
                val currentMessage = SmsMessage.createFromPdu(pdusObj[i] as ByteArray)
                val phoneNumber = currentMessage.displayOriginatingAddress
                val message = currentMessage.displayMessageBody
                Log.i("SmsReceiver", "senderNum: $phoneNumber; message: $message")
                // Show alert
                val toast = Toast.makeText(context,"senderNum: $phoneNumber, message: $message",Toast.LENGTH_LONG).show()

            } // end for loop
        } // bundle is null
    } catch (e: Exception) {
        Log.e("SmsReceiver", "Exception smsReceiver$e")
    }


}

}

您可以通過使用接口來做到這一點

在 SMSReceiver.kt class 中創建一個接口

class SMSReceiver.kt(val callback:ICallback) {
    interface ICallback{
        fun updateUI(value:String)
    }

    fun doSomething() {
       // your operations to perform some task. then call this
       callback.updateUI(/*Pass your data which you want to set to your textview*/ "")
    }
}


class ActivityReceive: SMSReciever.ICallback {

    override fun updateUI(value:String) {
        //set the data which you got from SMSReceiver class
        textview.text = value
    }
}

暫無
暫無

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

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