将布尔值从片段传递到托管活动

我有一个实现 ClickListener 的 Fragment。托管活动要么显示一个空白片段,要么在片段容器 (FrameLayout) 中显示单击的项目的值。


我正在处理旋转更改,我需要知道片段中是否单击了某个项目。如果已单击,我想显示所有方向更改的数据。如果没有点击任何东西,我想显示一个空白片段,它有一个简单的步骤,上面写着“请点击”。


我只需要知道如何将此布尔值传递回活动,我相信接口是一种选择,但需要一些编码帮助:


Adapter,它决定了在 Fragment 中单击项目时会发生什么:


    holder.itemView.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                FragmentTransaction transaction = mFragmanager.beginTransaction();

                if (position == 0){

                    IngredientsListFragment ingredientsListFragment = IngredientsListFragment.newInstance(mRecipeList, mRecipePosition, position, mIngredientsDataSet);

                    RecipeStepsFragmentTwo recipeStepsFragmentTwo = (RecipeStepsFragmentTwo) mFragmanager.findFragmentById(R.id.recipe_details_two);

                    transaction.remove(recipeStepsFragmentTwo);

                    transaction.add(R.id.recipe_details_three, ingredientsListFragment);

                    transaction.commit();


                } else {

                    RecipeStepsFragmentThree recipeStepsFragmentThree;

                    recipeStepsFragmentThree = RecipeStepsFragmentThree.newInstance(mRecipeList, mRecipePosition, (position -1));

                    //TODO: Why am I being prompted for V4? Am I handling correctly?


                    //TODO: Am I handling removal of previous frag correctly?

                  RecipeStepsFragmentTwo recipeStepsFragmentTwo = (RecipeStepsFragmentTwo) mFragmanager.findFragmentById(R.id.recipe_details_two);

                    transaction.remove(recipeStepsFragmentTwo);

                    transaction.add(R.id.recipe_details_three, recipeStepsFragmentThree);

                    transaction.commit();

                }



            }

        });


幕布斯7119047
浏览 188回答 2
2回答

catspeake

您可以通过 getActivity.isFlag=true 或 flase 简单地完成这里 isFlag 是活动中的布尔值,您可以通过 getActivity 访问它。

森林海

在 Fragment 中定义接口和抽象方法。如果您在 Adapter 中单击,则将此委托传递给适配器,或者最好在 Fragment 中单击。代码public class MyFragment extends Fragment{private Context mContext;public void onAttach(Activity activity) {        super.onAttach(activity);        this.mContext = activity;    }public void onActivityCreated(@Nullable Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        mDelegate = (Delegate) mContext;        ...        ...        ...        onclick -> {           mDelegate.passValue(value)          }}public interface Delegate{ public void passValue(boolean value);}在您的活动中public class MyActivity extends AppCompatActivity implements MyFragment. Delegate{    @override        public void passValue(boolean value){    } }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java