我有做一个片段交易安卓碎片无法获得活动
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是空的。我应该在哪里找到我的包?
EDIT2:
错过了在答复getArguments()。现在正在工作。
我的布局充气onViewCreated被调用。我可以看到我的布局。 – AndyAndroid 2012-07-31 18:02:57