如何设置接口侦听器以检测Kotlin中的变量更改。我成功用Java实现了以下内容,但在Kotlin中遇到了问题:
接口:
public interface InterfaceRefreshList
{
public void refreshListRequest();
}
包含侦听器的类:
public class SignalChange
{
private static boolean refreshListSwitch;
private static List<InterfaceRefreshList> refreshListListeners = new ArrayList<>();
public static void setRefreshList(boolean value)
{
refreshListSwitch = value;
for(InterfaceRefreshList l : refreshListListeners)
l.refreshListRequest();
}
public static void addRefreshListListener(InterfaceRefreshList l)
{
refreshListListeners.add(l);
}
}
侦听器正在侦听的类:
public class FragmentBrowse extends Fragment
{
public FragmentBrowse() /// Constructor
{
SignalChange.addRefreshListListener(() -> refreshList());
}
refreshList()
{
// do something
}
}
要发出更改信号:
SignalChange.setRefreshList(true);
我可以设置接口和信号类别:
class SignalChange
{
private var refreshListSwitch: Boolean = false
var setSwitch: Boolean
get() = refreshListSwitch
set(value)
{
refreshListSwitch = value
}
private var refreshListListeners = ArrayList<InterfaceRefreshPersonsList>()
fun sendRefreshSignal()
{
for(l in refreshListListeners) l.refreshPersonsList()
}
fun addRefreshListListener(l: InterfaceRefreshPersonsList)
{
refreshListListeners.add(l)
}
}
但是我无法在FragmentBrowse类中设置侦听器。片段类不允许构造函数。
答案 0 :(得分:4)
您可以使用内置的Kotlin委托,例如:
object SignalChange {
var refreshListListeners = ArrayList<InterfaceRefreshList>()
// fires off every time value of the property changes
var property1: String by Delegates.observable("initial value") { property, oldValue, newValue ->
// do your stuff here
refreshListListeners.forEach {
it.refreshListRequest()
}
}
}
interface InterfaceRefreshList {
fun refreshListRequest()
}
添加这样的侦听器:
SignalChange.refreshListListeners.add(object : InterfaceRefreshList {
override fun refreshListRequest() {
refreshList()
}
})
OR
可以使用 lambda 界面的界面:
object SignalChange {
var refreshListListeners = ArrayList<() -> Unit>()
// fires off every time value of the property changes
var property1: String by Delegates.observable("initial value") { property, oldValue, newValue ->
// do your stuff here
refreshListListeners.forEach {
it()
}
}
}
要添加侦听器,只需调用:
SignalChange.refreshListListeners.add(::refreshList)
//or
SignalChange.refreshListListeners.add { refreshList() }
fun refreshList() {
}
答案 1 :(得分:3)
在 KOTLIN
中使用简单方式收听变量的方法private var myVariableName by Delegates.observable(0) { property, oldValue, newValue ->
Log.d(TAG,"New Value $newValue")
Log.d(TAG,"Old Value $oldValue")
}
有关更多信息,请阅读https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/