如何在重新创建片段之前保存数据?

时间:2016-07-17 19:47:01

标签: android android-fragments

我尝试使用fragment子类中的onSaveInstanceState(Bundle outState)方法保存数据。

说明:     我创建了一个类FragmentA,它扩展了这个类中的Fragment我有一个变量名计数,当我点击按钮时,count的值是变化的(最初计数= 0)我想保存计数值甚至方向改变(肖像到横向或反之亦然) 。 我的MainActivity类动态加载片段。

我的代码:

此课程扩展片段: -

public class FragmentA extends Fragment implements View.OnClickListener {
Button change_After_Click;
    int count=0;
    Communicator com;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState!=null){
            count=savedInstanceState.getInt("counter",0);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a_layout, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("onActivityCreated");
        com= (Communicator) getActivity();
        change_After_Click=(Button)getActivity().findViewById(R.id.textChangeClick);
        change_After_Click.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

count=count+1;
        com.proviedLinkBothFragment("button click "+ count);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("counter",count);
    }
}

这里的MainActivity类我动态加载片段: -

public class MainActivity extends AppCompatActivity implements Communicator {
Button btn;
    FragmentManager   fragmentManager;
    FragmentTransaction fragmentTransaction;
    FragmentB obj;
    FragmentA objA;

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

        System.out.println("ge low");


                    fragmentManager=getSupportFragmentManager();
                    fragmentTransaction=fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.relativeLayout,new FragmentA());

                    fragmentTransaction.commit();




    }



    @Override
    public void proviedLinkBothFragment(String s) {

           FragmentB fb= (FragmentB) fragmentManager.findFragmentById(R.id.relativeLayout);
        fb.changeText(s);


    }


}

1 个答案:

答案 0 :(得分:0)

在活动的方法onCreate中,您应该在替换之前检查片段是否已存在。添加片段时,您应该使用此片段的标签(“MY_TAG”),之后您可以通过标签找到片段。您不需要手动重新创建片段(我想在旋转期间)。系统为您服务。

fragmentManager=getSupportFragmentManager();
if (fragmentManager.findFragmentByTag("MY_TAG") == null) {
    fragmentTransaction=fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.relativeLayout,new FragmentA(), "MY_TAG");

    fragmentTransaction.commit();
}