Android - 在视图中显示带有自定义文本的片段

Android - show fragment with custom text in view

我需要在屏幕上显示几个片段。所有片段都是一个片段 class 的实例,但我需要能够设置我的值以查看这些片段的属性(例如 TextView 中的文本)。我从这里尝试了很多解决方案,但没有找到一个。 我现在在做什么:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction = manager.beginTransaction();
List<Comment> comments = place.getComments();
int i = 0;
for (Comment comment : comments) { //some cycle...

     ReviewFragment reviewFragment = new ReviewFragment();
     transaction.add(scrollView.getId(), reviewFragment, "review" + i);
     ((TextView) reviewFragment.getView().findViewById(R.id.author)).setText(comment.getAuthor());
     i++;

}
transaction.commit();

但我得到 NullPointerException:reviewFragment.getView() 为空。我尝试在每个片段之后提交事务并开始新的事务,但没有帮助。如何在片段视图中设置自定义值?

P.S。我没有在 ReviewFragment 的重写方法中做一些特别的事情。我应该吗?

谢谢!

您可以调用片段的方法setArguments() when you construct your fragment and pass the text you would like to display. Then inside the ReviewFragment class you can call getArguments()来检索文本并显示它。

在您创建片段的部分:

ReviewFragment reviewFragment = new ReviewFragment();
Bundle args = new Bundle();
args.putString("text", "The text to display here");
reviewFragment.setArguments(args);
transaction.add(scrollView.getId(), reviewFragment, "review" + i);

并在 ReviewFragment 的 onCreateView() 中

// after inflating the view and before returning it
String textToDisplay = getArguments().getString("text");
myTextView.setText(textToDisplay);