【问题标题】:Add a button dynamically from one fragment to another [duplicate]将按钮从一个片段动态添加到另一个[重复]
【发布时间】:2018-02-07 10:58:44
【问题描述】:

我正在构建一个 android 应用程序,但我对它相当陌生。我想知道是否有一种方法可以通过按下另一个片段上的按钮来动态地将按钮添加到片段中。例如,我有一个片段 (A),它保存来自用户的输入并将其显示在片段 (B) 上的列表视图中,因此我想为每个用户输入在片段 (B) 中添加一个按钮。

Fragment A

Popup window when fab is clicked (B)

【问题讨论】:

标签: java android android-fragments


【解决方案1】:

目前尚不清楚它是如何在应用程序中实现的。假设两个片段在活动中同时显示。在这种情况下,您可以使用FragmentManager 获取对另一个片段的引用:

((MyFragment) getFragmentManager().findFragmentById(...)).addButton(myArgs)

如果它们被放置在不同的活动中或者如果一个替换另一个,则需要使用参数Bundle在两者之间传递信息:

SecondFragment secondFragment = new SecondFragment();
Bundle args = new Bundle;
args.putString("name", "batman");
secondFragment.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.container, secondFragment).commit();

// later in SecondFragment#onViewCreated
button.setText(getArgments.getString("name"));

【讨论】:

    【解决方案2】:

    片段之间的通信可以通过“接口”进行。您通过链接片段的活动传递数据。 Fragment B 接收到相应的数据后,可以执行一定的动作,刷新 Fragment 以显示结果。

    有关执行的更多信息,请参阅以下链接- passing data between fragments

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多