0

实际上我的问题是我想在按钮clickListner上将字符串从主活动发送到我的片段但是当我从主活动调用片段函数时,片段的onCreateView再次调用并且一切都再次初始化。请指导我如何避免这个问题谢谢。

这是我的 MainActivity 代码:

ThirdFragment thirdFragment=new ThirdFragment();
                            FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction().add(R.id.thirdfragment,thirdFragment,null);
                           fragmentTransaction.commitNow();
                            ThirdFragment fragment = (ThirdFragment) getSupportFragmentManager().findFragmentById(R.id.thirdfragment);
                           if(fragment!=null) {
                               fragment.Subcategories(text);

                           } 

这是片段功能代码:

public void Subcategories(String text){

    Log.d(TAG, "Subcategories: fragment calling "+text);

        mAPIService.searchcategory("2",text).enqueue(new Callback<ArrayList<DataStored>>() {
            @Override
            public void onResponse(Call<ArrayList<DataStored>> call, Response<ArrayList<DataStored>> response) {
               myRecyclerAdapter.addItems(response.body());
            }
            @Override
            public void onFailure(Call<ArrayList<DataStored>> call, Throwable t) {
                myRecyclerAdapter.addItems(null);


            }
        });


}
4

1 回答 1

0

试试这样;`

 ThirdFragment thirdFragment=new ThirdFragment();
    FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction().replace(R.id.thirdfragment,thirdFragment,null);
                               fragmentTransaction.commitNow();
                                ThirdFragment fragment = (ThirdFragment) getSupportFragmentManager().findFragmentById(R.id.thirdfragment);
                               if(fragment!=null) {
                                   fragment.Subcategories(text);

                               } `
于 2018-07-07T17:44:04.777 回答