每当我按下我的应用程序的后退按钮时,都会发生以下情况。
原 手机显示:FragA
点击FragA上的视图后 手机显示:FragB
点击后退按钮后 手机显示: 弗拉加 弗拉加
我不知道为什么会重新创建FragA,但是当按下后退按钮时会将其添加到上一个FragA的末尾。以下是我的代码。
public class ColorListFragment extends ListFragment {
private List<ColorGD> mDrawableList = null;
private ColorAdapter mAdapter = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_color_list, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
populateList();
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ColorGD viewItem = mDrawableList.get(position);
float[] hues = {viewItem.getColor(0),viewItem.getColor(1)};
Bundle args = new Bundle();
final String hueValues = "hues";
args.putFloatArray(hueValues,hues);
SaturationListFragment sLF = new SaturationListFragment();
sLF.setArguments(args);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,sLF);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
我的主要活动有以下
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListFragment();
}
public void addListFragment(){
ColorListFragment cLF = new ColorListFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,cLF);
transaction.commit();
}
}
答案 0 :(得分:4)
我想我知道这里发生了什么。 Fragment
实际上不可能只与一个视图容器重复。
我怀疑由于ListFragment
中对populateList()
的调用,onActivityCreated()
中的项目会重复。
因为每次点击后退按钮从onActivityCreated()
返回ColorListFragment
时都会调用SaturationListFragment
,所以每次都会调用populateList()
。见documentation here
要解决您的问题,只需将通话移至populateList()
至onCreate()
,这仅在ListFragment
首次初始化时调用:
public class ColorListFragment extends ListFragment {
private List<ColorGD> mDrawableList = null;
private ColorAdapter mAdapter = null;
//add the onCreate() override
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
populateList(); //add this here
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_color_list, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//populateList(); //remove this
//..................