我有一个用电容器构建的混合应用程序,但是我需要实现一些本机代码以使用 android 演示类来使用辅助显示器。我需要根据从电容器接收到的数据更新我的演示视图,实现此目的的最佳设计模式是什么?
这是我的适配器
class CartItemAdapter(context: Context, private val cartItems: List<CartItem>) : ArrayAdapter<CartItem>(context, 0, cartItems) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.customer_list_item, parent, false)
val item = getItem(position) ?: return view // Safely unwrapping
// Bind the view elements to your data
view.findViewById<TextView>(R.id.itemDescription).text = item.description
return view
}
}
这是我的电容器插件方法,它被调用并从电容器接收数据:
@PluginMethod
fun transactionChange(call: PluginCall){
val itemsJson = call.getString("items")
println(itemsJson)
val transaction = itemsJson?.let { Json.decodeFromString<Transaction>(it) }
transaction?.let {
}
val ret = JSObject()
ret.put("items", transaction)
call.resolve(ret)
}
suspend fun login(): User {
val credentials = Credentials.anonymous()
return app.login(credentials)
}
}```
What is the best way to update my view in the seperate class?
I have tried calling a companion method, however that requires a context and I understand that passing that context in is an anti pattern, I'm just trying to find the correct design pattern for this.
这不是一个很好的答案,因为我从未使用过Presentation,也没有测试过它。但我认为就像使用 Activity 或 Fragment 一样,您设置内容视图,然后获取对其中所需视图的引用并对它们执行操作。
不幸的是,
lifecycleScope
(在 UI 层中运行协程的典型方法)将不可用,因为它不是 Activity 或 Fragment。因此,您需要为此创建一个 CoroutineScope,并在演示文稿被销毁时将其取消,以避免泄漏。
所以我认为你的代码看起来大概是这样的:
class MyPresentation(
display: Display,
context: Context
) : Presentation(context, display) {
private val scope = MainScope()
init {
setOnDismissListener { scope.cancel() }
}
// ...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.customer_display)
val recyclerView = findViewById(R.id.recycler_view)
val adapter = CartItemAdapter(context, emptyList())
recyclerView.adapter = adapter
// I don't know anything about Capacitor but let's assume you have some
// sort of reference to it here.
scope.launch {
val loginResult = capacitorPlugin.login()
// do something with login result, maybe update some views?
val dataList = capacitorPlugin.getSomeData()
adapter.cartItems = dataList // you'll have to make cartItems a public var
adapter.notifyDataSetChanged()
}
}
}