带有自定义片段类对象的Android Studio片段



我刚刚在我的应用程序中创建了一个由一些控件组成的片段。原则上,我希望这些控件通过tcp客户端发送其当前数据,该客户端具有与tcp套接字相关的方法TcpClient::sendMessage。片段本身由一个接口组成,该接口用于创建对保存片段的MainActivity的回调。这就是我如何将碎片附加到我的MainActivity:

FragmentControls fragmentControls = new FragmentControls((command, message) -> tcp_client.sendMessage(command, message));
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragment_pi_connected, FragmentControls.class, null)
.commit();

我如何在第一行创建带有初始化对象fragmentControls的Fragment来实现接口功能?

为了完整起见,我的Fragment类:

public class FragmentControls extends Fragment {
public CommandSendInterface commandSendInterface;
public FragmentControls(CommandSendInterface sendCommandInterface) {
super(R.layout.maunal_pi_controls);
commandSendInterface = sendCommandInterface;
}
// Some stuff that handles the View Objects in the Fragment and treats their events...
public interface CommandSendInterface{
void onCommandSend(ServerCommands command, int message);
}
}

本应将对象作为参数而不是.class值传递,现在它工作得很好。

最新更新