当前位置: 首页 > 知识库问答 >
问题:

如何让一个方法同时与一个活动和一个片段进行通信?

端木兴国
2023-03-14

我也看了这段视频,并阅读了以下问题:

>

  • 共享ViewModel以帮助片段和父活动之间的通信

    从另一个片段调用fragmentMethod,但不能在ParentFragmentActivity的视图分页器中引用它们

    “我的上帝”对这个问题的答复很有帮助,但我仍然不确定在我的情况下做什么是最好的事情,因为我有一个用户可以输入数据的片段,而相同的片段也应该查看数据作为输入的结果。(也许我的第一个错误是这样构建app?)

    我提供了一些代码,以防有帮助。

    public class AccuracyFragment extends Fragment {
        EditText editTextLevel, editTextAccuracy; 
        private OnFragmentInteractionListener mListener;
    
        public AccuracyFragment() {
            // Required empty public constructor
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_accuracy, container, false);
            editTextAccuracy = view.findViewById(R.id.text_accuracy_character);
            editTextLevel = view.findViewById(R.id.text_level_character);
    
    
            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    //Doing nothing
    
                }
    
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    //Doing nothing
    
                }
    
                @Override
                public void afterTextChanged(Editable editable) {
                    updateFragment(Float.valueOf(editTextLevel.getText().toString()), Float.valueOf(editTextAccuracy.getText().toString()));
                }
            };
    
            editTextLevel.addTextChangedListener(watcher);
            editTextAccuracy.addTextChangedListener(watcher);
    
            return view;
        }
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceof OnFragmentInteractionListener) {
                mListener = (OnFragmentInteractionListener) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            mListener = null; //I don’t know what this does
        }
    
        @Override
        public void onResume() {
            super.onResume();
    //        updateFragment(); //Should I have this? 
        }
    
        public interface OnFragmentInteractionListener {
            String[] onAccuracyFragmentInputChanged(float levelFromFragment, float accuracyFromFragment);    }
    
        public void updateFragment(float level, float accuracy) {
    
            //Complicated method doing things with editTextLevel and editTextAccuracy. However, it doesn’t work when this method is called from outside AccuracyFragment – EditTexts are null
    
    
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
        }
    
        @Override
        public void onPause() {
            super.onPause();
        }
    
        @Override
        public void onDestroyView() {
            super.onDestroyView();
        }
    
        @Override
        public void onStop() {
            super.onStop();
        }
    }
     
    public class MainActivity extends AppCompatActivity implements AccuracyFragment.OnFragmentInteractionListener, AdapterView.OnItemSelectedListener {
    
    
    
    
        AccuracyFragment accuracyFragment;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main_new); 
            selectedID = null;
            textView1 = (TextView) findViewById(R.id.text_1);
    textView2 =  (TextView) findViewById(R.id.text_2); 
    
    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout
    if (findViewById(R.id.fragment_container) != null) {
    // However, if we're being restored from a previous state, then we don't need to do anything and should return or else we could end up with overlapping fragments.
    if (savedInstanceState != null) {
        return;
    }
    
    // Create a new Fragment to be placed in the activity layout
    accuracyFragment = new AccuracyFragment();       
     }
    }
    //This is the core method which takes the value from two EditTexts in the Fragment, and two TextViews in the MainActivity
        private String[] getRequiredAccuracy(float firstValueFromActivity, float secondValueFromActivity, float firstValueFromFragment, float secondValueFromFragment) {
    
    //This methods uses parameters from the Activity, and two from the Fragment, and is intended to be called from both the Activity and from the Fragment itself
    
            String returnValues[] = {s, q, r, c}; //This method is too complex to show, but it will end up outputting some values
            return returnValues;
        }
    
    
    
        public void methodCalledUponClick(View view) {
    //After showing a Dialog with some choices, I intend to call the method from fragment:
            accuracyFragment.updateFragment();
        }
    
        @Override
        public String[] onAccuracyFragmentInputChanged(float levelFromFragment, float accuracyFromFragment) {
            String returnValues[] = {"0", "0", "0"};
            if (selectedID != null) {
                if (textView1.length() == 0 || textView2.length() == 0) {
                    //Do nothing if any of these are empty
                } else {
                    returnValues = getRequiredAccuracy(Float.valueOf(textView1.getText().toString()), Float.valueOf(textView2.getText().toString()), levelFromFragment, accuracyFromFragment);
                }
            }
            return returnValues;
        }
    
    }
    
    }
    
  • 共有1个答案

    令狐嘉禧
    2023-03-14

    您可以继续使用回调/接口来同时与片段和活动通信。

    用于创建回调/接口:

    public interface CallBackListener {
    void onCallBack(String value);// pass any parameter in your onCallBack which you want to return 
    }
    

    在片段类中:

    public class AccuracyFragment extends Fragment {
    
    private CallBackListener callBackListener;
    
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //getActivity() is fully created in onActivityCreated and instanceOf differentiate it between different Activities
        if (getActivity() instanceof CallBackListener)
            callBackListener = (CallBackListener) getActivity();
    }
    
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        EditText editText = (EditText) view.findViewById(R.id.edittext);
        editText.addTextChangedListener(new TextWatcher() {
    
        @Override
        public void afterTextChanged(Editable s) {}
    
         @Override    
         public void beforeTextChanged(CharSequence s, int start,
          int count, int after) {
         }
    
        @Override    
        public void onTextChanged(CharSequence s, int start,
         int before, int count) {
            if(callBackListener != null)
                    callBackListener.onCallBack(s.toString());
            }
        });
      }
    }
    
    public class MainActivity extends AppCompatActivity  implements CallBackListener
     {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    }
    
     @Override
     public void onCallBack(String value) {
        Toast.makeText(mContext,"onCallback Called",Toast.LENGTH_LONG).show();
     }
    }
    
     类似资料:
    • 在我的应用程序中,我使用了一个活动和两个片段。该应用程序使用带有容器的布局,因此片段是通过事务添加的。第一个片段包含列表视图,另一个片段包含列表视图项的详细视图。两个片段都使用setRetainInstance(true)。片段是通过替换事务添加的,并设置了addToBackStack(null)。列表片段包含一个实例变量,其中包含列表的一些信息。现在我正在切换到详细并按回,实例变量为null。我

    • 我已经完成了导航,现在进入第一个片段。在第一个片段中有两个按钮,我需要通过按下这些按钮来切换到一个新的活动。我不明白如何正确地实施它。我犯了一个错误。 代码,eror

    • 问题内容: 我在小组活动中有一个片段,我想用另一个片段替换它: 在不使用活动组的情况下作为单独的项目完成时,它工作正常,当控件进入getview()时,每件事在日志猫中都可以正常工作,但是没有视图可见,甚至没有任何异常出现,我希望将书详细信息片段由部分详细信息片段代替。 图书详细信息片段的XML具有id book_description_fragment,而部分描述片段的xml具有id secti

    • 我想在Android的一个活动中添加两个片段。但在加法时,它给出了错误; activity_main.xml 片段的布局1 片段2的布局

    • 先生/女士,我想使用android JAVA将一个片段回调到另一个片段。我试图找到问题,但没有找到解决方案。若我使用接口,它会向活动发送回调响应,这是我不想要的。非常感谢。