android-fragments 带有自定义片段类对象的Android Studio Fragment

brqmpdu1  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(139)

我刚刚在我的应用程序中创建了一个片段,其中包含一些控件。原则上,我希望这些控件通过一个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);
    }
}
laik7k3q

laik7k3q1#

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

相关问题