添加的片段未被删除并导致应用程序崩溃

时间:2014-06-20 10:45:25

标签: android android-fragments

添加片段工作正常,但删除它会导致应用崩溃。我认为删除将是直接的,但我仍然是一个初学者,所以我必须遗漏一些东西。你能看看吗?

public class MainActivity extends Activity implements OnClickListener {

    Button addFragment, closeFragment;
    android.app.FragmentManager fragmentManager = getFragmentManager();
    android.app.FragmentTransaction transaction = fragmentManager
            .beginTransaction();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
    }

    private void initialize() {
        addFragment = (Button) findViewById(R.id.bAddF);
        closeFragment = (Button) findViewById(R.id.bCloseF);
        addFragment
                .setOnClickListener((android.view.View.OnClickListener) this);
        closeFragment
                .setOnClickListener((android.view.View.OnClickListener) this);
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
            //Instantiate fragment from ExampleFragment class
             ExampleFragment fragment = new ExampleFragment();
             switch(arg0.getId()){      
                 case R.id.bAddF:
                      transaction.add(R.id.fragment_holder, fragment).commit();
                 break;
                 case R.id.bCloseF:
                      transaction.remove(fragment).commit();
                 break;
             }
    }

}

1 个答案:

答案 0 :(得分:1)

您的应用崩溃是因为您将FragmentTransaction保存为成员变量。但FragmentTransactions 无法重复使用。此外,您每次都会创建一个新的Fragment,这意味着点击删除Fragment时,系统不会删除当前添加的Button

这样做:

    private ExampleFragment mFragment;

    @Override
    public void onClick(View v) {

          //Instantiate fragment from ExampleFragment class
          if(mFragment == null) mFragment = new ExampleFragment();

          switch(v.getId()){      
              case R.id.bAddF:
                 getFragmentManager().beginTransaction().add(R.id.fragment_holder, mFragment, "tag").commit();
                 break;
              case R.id.bCloseF:
                 getFragmentManager().beginTransaction().remove(mFragment).commit();
                 break;
          }
     }

为每个add()或remove()过程创建一个新的FragmentTransaction

作为将ExampleFragment保留为成员变量的替代方法,您可以使用FragmentManager.findFragmentByTag("tag")来获取当前添加的片段。

替代方式:

    @Override
    public void onClick(View v) {

          switch(v.getId()){      
              case R.id.bAddF:
                 getFragmentManager().beginTransaction().add(R.id.fragment_holder, new ExampleFragment(), "tag").commit();
                 break;
              case R.id.bCloseF:
                 Fragment frag = getFragmentManager().findFragmentByTag("tag");
                 getFragmentManager().beginTransaction().remove(frag).commit();
                 break;
          }
     }