【发布时间】:2012-07-31 15:11:22
【问题描述】:
我有一个进行片段事务的活动
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();
我的片段 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");
}
savedInstranceState 似乎是空的。我应该在哪里找到我的捆绑包?
编辑2:
在回复中错过了 getArguments()。现在正在工作。
【问题讨论】: