我有一个活动,其中进行了片段事务
DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();
这个很好。现在我知道我的活动中有一个动态字符串,我需要替换我在newFragment中的布局。我认为我可以在transaction.commit()之后调用类似于以下内容的东西:
newFragment.setMyString("my dynamic value");
在 newFragment.java 文件中,我有以下内容:
public void setMyString(String s)
{
TextView tv = (TextView) getActivity().findViewById(R.id.myobject);
tv.setText(s);
}
问题在于getActivity()返回null。我该如何获取所需的上下文来查找我的布局元素?
编辑:
我尝试按照捆绑包的方式进行,因为这似乎是最干净的方法。所以我已经改变了我的代码:
Bundle b = new Bundle();
b.putString("text", "my dynamic Text");
DetailFragment newFragment = new DetailFragment();
transaction.replace(R.id.mylist, newFragment);
transaction.addToBackStack(null);
transaction.commit();
我的fragment的onCreateView方法如下所示:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.mylayout, container, false);
TextView t = (TextView) v.findViewById(R.id.texttobereplaced);
t.setText(savedInstanceState.getString("text");
}
看起来savedInstanceState是空的。我应该在哪里找到我的bundle?
编辑2:
回复中漏掉了getArguments()。现在正在工作。
onActivityCreated
之前,Fragment
将附加到一个null
的活动上...也就是说,如果在onCreate
或onCreateView
中调用getActivity()
,它将返回null
,因为Activity
还没有被创建。所以请确保您所有对getActivity()
的调用都在onActivityCreated
中或之后进行。 - Alex LockwoodonAttach()
之后调用getActivity()
,活动就应该可用。我编辑了我的原始回答来解决这个问题...说实话,我不确定这个答案为什么会有5个赞。我想我两年前更像一个新手。:P - Alex Lockwood