0

我只是想知道如何在创建 Fragment 之前将参数或参数发送到它。因为我想将一个字符串数组传递给片段,以便它可以在创建时将所有字符串放入布局中。例如,我正在制作一个排行榜片段,我的活动将传递该片段将用于显示的所有分数等。我知道我可以使用 Bundle 和 .setArgs 但这对我的情况有用吗?谢谢

** 编辑 **

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View singleplayerView = inflater.inflate(R.layout.singleplayer_tab, container, false);
        String[] scores = (String[]) getArguments().get("scores");
        TextView tview = (TextView) singleplayerView.findViewById(R.id.player_name0);
        tview.setText(scores[0]);
        setupRank(singleplayerView);
        return singleplayerView;
    }

    public static SingleplayerTab newInstance(String[] scores) {
        SingleplayerTab spt = new SingleplayerTab();
        Bundle args = new Bundle();
        args.putStringArray("scores", scores);
        spt.setArguments(args);
        return spt;
    }

调用它的代码

String[] scores = {"hello"};
Fragment singlePlayerFragment = SingleplayerTab.newInstance(scores);
4

1 回答 1

2

我知道我可以使用 Bundle 和 .setArgs 但这对我的情况有用吗?

ABundle可以容纳一个String[]或一个ArrayList<String>

此外,这是您应该这样做的方式,而不是自定义构造函数。Android 会在配置更改(例如,屏幕旋转)时自动重新创建您的片段,并且它会为此使用您的公共零参数构造函数。因此,除非您使用 argumentsBundle或其他东西,否则您将在配置更改时丢失您的字符串数组。

推荐的方法是使用工厂方法,例如来自 的这个EditorFragment

  static EditorFragment newInstance(int position) {
    EditorFragment frag=new EditorFragment();
    Bundle args=new Bundle();

    args.putInt(KEY_POSITION, position);
    frag.setArguments(args);

    return(frag);
  }

在这种情况下,我想传入int position片段。我将其隔离包装到Bundle工厂方法(newInstance())中。当我需要创建此片段的实例时,我调用EditorFragment.newInstance()而不是new EditorFragment,因此我可以提供position. 我的片段可以position通过读取KEY_POSITION. 我在这个示例项目getArguments() Bundle(以及其他地方)中使用了这种方法,展示了将 10 个这些编辑器加载到一个.ViewPager

于 2013-05-26T06:25:45.557 回答