我有一个应用,其中包括一个活动和一个片段。在活动中,som数据使用TextViews显示,在Fragment中,用户可以使用EditText-views输入一些数据。我有一个方法从Activity和Fragment中获取数据,执行一些计算,最后在Fragment和Activity中显示结果。如果在Fragment中的任何EditText视图中编辑文本后调用,则此方法当前有效。但是,我也想在每次更新Activity中的数据时都调用它,但是当我尝试这样做时,由于它们返回null,因此无法获取EditText数据。 因此,我的问题是:什么是优良作法,或者当处理应该从活动和片段中获取的方法时要做的“正确方法”?如果有人可以带领我走上正确的道路,我将不胜感激。
我已阅读official documentation on Fragments,并提到了ViewModel。但这似乎不适用于我的应用程序,因为我希望参与该活动。我需要使用此功能还是可以进行主要活动?我还阅读了有关接口的信息,但不确定哪个接口最适合我的项目。我目前正在使用接口,但是不确定是否正确使用了。
我也看过this video并阅读了以下问题:
“我的上帝”对this question的回复很有帮助,但是我仍然不确定在我的情况下最好做些什么,因为我有一个供用户输入数据的Fragment,片段还应查看作为该输入结果的数据。 (也许我的第一个错误就是这样构建应用程序?)
如果有帮助,我会提供一些代码。
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;
}
}
}
答案 0 :(得分:0)
您可以继续进行回调/接口以同时与片段和活动进行通信。
用于创建回调/接口:
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();
}
}