如何以编程方式添加和删除片段?

时间:2015-09-12 16:54:21

标签: android android-fragments

我希望在设备处于横向模式时添加片段,并在设备处于纵向模式时删除此片段。当设备处于横向模式时,我能够添加片段。当设备返回纵向模式时,我调用remove方法,但片段仍显示。

以下是执行片段添加和删除的代码:

public void addingFragment_programatically()
{
    final String PREF_STATE="preference_state";

    SharedPreferences sPref=getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editer=sPref.edit();
    Boolean configState=sPref.getBoolean(PREF_STATE, false);
    Fragment_Base fragment_base=Fragment_Base.newInstance("text passed 
    in during Instantiation","");

    Configuration config=getResources().getConfiguration();
    FragmentManager fragmentManager= getFragmentManager();
    FragmentTransaction       
    fragmentTransaction=fragmentManager.beginTransaction();

    if(config.orientation==Configuration.ORIENTATION_LANDSCAPE)
    {
        fragmentTransaction.add(R.id.layoutbelow, fragment_base);
        configState=true;
        editer.putBoolean(PREF_STATE,configState);
        editer.commit();

    }
    else if(configState)
    {
        fragmentTransaction.remove(fragment_base);
        configState=false;
        editer.putBoolean(PREF_STATE,configState);
        editer.commit();

    }

    fragmentTransaction.commit();
}

R.id.layoutbelow是一个线性布局id,充当片段的viewGroup,它在此活动类的xml布局中定义。 我希望有人可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

getFragmentManager().beginTransaction().remove(fragmentObject).commit();

为我工作。您可以使用onConfigurationChanged()方法检查您的方向是纵向还是横向。

答案 1 :(得分:0)

试试这个,

在AndroidManifest中添加public class MainActivity extends Activity { LoginFragment loginFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); // object of fragment loginFragment = new LoginFragment(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // landscape mode if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){ // add fragment(where to place, fragment object, fragment tag) getFragmentManager().beginTransaction().add(R.id.loginFrame,loginFragment,"loginFrame").commit(); } // portrait mode else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { // remove fragment with passing fragment object getFragmentManager().beginTransaction().remove(loginFragment).commit(); } } }

MainActivity.java

public class LoginFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // view to render
        View loginView = inflater.inflate(R.layout.login_fragment,null);
        return loginView;
    }
}

LoginFragment.java

*

这可能会对你有帮助。