我有做一個片段交易安卓碎片無法獲得活動
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