如何在 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类中设置监听器。片段类不允许构造函数。