ListFragment充气两次 [英] ListFragment is inflated twice
问题描述
我有被夸大了ListFragment(在skeleton.xml layout_container
)的线性布局( menufragment
)当创建的活性。然后,当用户进行点击,这样的布局被替换为另一个ListFragment( albumsfragment
)。
I have a linear layout (layout_container
in skeleton.xml) which is inflated with a ListFragment (menufragment
) when the activity is created. Then, when the user performs a click, this layout is replaced with another ListFragment (albumsfragment
).
问题是,当我preSS后退按钮,我回去的确给menufragment但名单是长两倍,因为它已经与相同的项目再次填满。我怎么能避免这种情况?
The problem is that when I press the back button, I go back indeed to the menufragment but the list is twice longer because it has been filled up again with the same items. How could I avoid this ?
onCreate方法,活动在
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.skeleton);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
MenuFragment menufragment = new MenuFragment();
fragmentTransaction.add(R.id.layout_container, menufragment, "menufragment");
fragmentTransaction.commit();
}
OnClick方法,活动在
public void OnMenuClick() {
AlbumsFragment albumsfragment = new AlbumsFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.layout_container, albumsfragment, "albumsfragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
我的片段类code:
public class MenuFragment extends ListFragment{
ArrayList<MenuItem> m_parts = new ArrayList<MenuItem>();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MenuAdapter m_adapter;
m_parts.add(new MenuItem ("item1"));
m_parts.add(new MenuItem ("item2"));
m_parts.add(new MenuItem ("item3"));
m_parts.add(new MenuItem ("item4"));
m_adapter = new MenuAdapter(getActivity(), R.layout.menu_row, m_parts);
setListAdapter(m_adapter);
所以我每次回去从AlbumFragment到MenuFragment,在MenuFragment列表中成长,如项目1,项目2,项目3,ITEM4再次加入。
So each time I go back from AlbumFragment to MenuFragment, the list in MenuFragment grows as item1,item2,item3,item4 are added once again.
我已经尝试添加检查如果(savedInstanceState == NULL)
的MenuFragment的交易之前,但不会改变任何东西。
I've try to add the check if (savedInstanceState == null)
before the transaction of the MenuFragment but doesn't change anything.
我应该怎么做才能让MenuFragment从后面堆栈弹出而不被这些项目再次膨胀?
What should I do to make MenuFragment be popped up from the back Stack without being inflated again with these items ?
感谢。
推荐答案
看看的的片段生命周期。 onActivityCreated()
返回到片段
时,将被称为每次。尝试,相反,你的执行移至的onCreate()
并应解决您重复的问题。
Take a look at the Fragment lifecycle. onActivityCreated()
will be called everytime when returning to aFragment
. Try, instead, to move your implementation to onCreate()
and that should fix your duplication issue.
这篇关于ListFragment充气两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!