Различные способы создания фрагмента - PullRequest
0 голосов
/ 30 декабря 2018

В приведенном ниже коде я хотел бы знать разницу между созданием экземпляра статического фрагмента, как показано в code_1 ниже.Я разместил код фрагмента, как показано в разделе code_2 ниже.

Пожалуйста, дайте мне знать разницу между двумя типами экземпляров и временем, когда использовать каждый из них.

код_1 :

  StudentMVCView mStudentMVCViewInitializedInstance = (StudentMVCView) this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
  Fragment mStudentMVCViewFragmentInitializedInstance = this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);

код_2 :

public class StudentMVCView extends Fragment implements View.OnClickListener{

private final static String TAG_LOG = StudentMVCView.class.getSimpleName();
private View mMainView = null;
private TextView mTextViewValue = null;
private EditText mEditTextValue = null;
private Button mBtn = null;
private TextView mTextViewBtnValue = null;
private StudentMVCModel mStudentMVCModel = null;
private int counter = 1;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    Log.v(TAG_LOG, "onCreateView");
    this.mMainView = inflater.inflate(R.layout.mvc_view_layout, null);
    this.mTextViewValue = this.mMainView.findViewById(R.id.mvc_view_textView_value);
    this.mEditTextValue = this.mMainView.findViewById(R.id.mvc_view_editText_value);
    this.mBtn = this.mMainView.findViewById(R.id.mvc_view_button);
    this.mBtn.setOnClickListener(this);
    this.mTextViewBtnValue = this.mMainView.findViewById(R.id.mvc_view_textView_btnValue);

    return this.mMainView;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Log.v(TAG_LOG, "onViewCreated");
    view.findViewById(R.id.mvc_view_textView_value);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.v(TAG_LOG, "onActivityCreated");
    Bundle bundledArgs = this.getArguments();
    StudentMVCModel studentMVCModel = (StudentMVCModel) this.getSerializedfromBundle(bundledArgs, "p");
    Log.v(TAG_LOG, "studentMVCModel.getStudentId()" +  studentMVCModel.getStudentId());

    this.setStudentMVCModelObject(studentMVCModel);
}

private void setStudentMVCModelObject(StudentMVCModel studentMVCModel) {
    this.mStudentMVCModel = studentMVCModel;
}

private StudentMVCModel getStudentMVCModelObject() {
    return this.mStudentMVCModel;
}
private Bundle getBundledArguments() {
    Log.d(TAG_LOG, "getBundledArguments");
    if (this.getArguments() !=null) {
        return this.getArguments();
    } else {
        Log.e(TAG_LOG, "this.getArguments() is NULL.");
        throw new NullPointerException("getArguments is NULL");
    }
}
private Object getSerializedfromBundle(Bundle bundle, String key) {
    Log.d(TAG_LOG, "getSerializedfromBundle");
    if (bundle != null) {
        return bundle.get(key);
    } else {
        Log.e(TAG_LOG, "bundle is NULL.");
        throw new NullPointerException("bundle is null");
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.v(TAG_LOG, "onDestroy");
}

public void setStudentIdToView(int id) {
    if (this.mMainView != null) {
        TextView textView = this.mMainView.findViewById(R.id.mvc_view_textView_value);
        Log.v(TAG_LOG, "TextView contains: " + textView.getText().toString());
    }
}

public void setTextViewValueFor(int id) {
    if (this.mTextViewValue != null) {
        this.mTextViewValue.setText("" + id);
    } else {
        Log.e(TAG_LOG, "setTextViewValueFor is NULL.");
    }
}

public void setEditTextValueFor(String str) {
    if (this.mEditTextValue != null) {
        this.mEditTextValue.setText(str);
    } else {
        Log.e(TAG_LOG, "mEditTextValue is NULL.");
    }
}

public void clearEditText() {
    if (this.mEditTextValue != null) {
        this.mEditTextValue.setText("");
    } else {
        Log.e(TAG_LOG, "mEditTextValue is NULL.");
    }
}

@Override
public void onClick(View v) {
    int id = this.getStudentMVCModelObject().getStudentId();
    Log.i(TAG_LOG, "onClick: id: " + id + " counter: " + counter++);
}
}

1 Ответ

0 голосов
/ 31 декабря 2018

В первой строке вы приводите фрагмент к типу StudentMVCView, поэтому вы можете получить доступ к дополнительным элементам, добавленным к нему, например setTextViewValueFor(int id), setEditTextValueFor(String str), ..etc

  StudentMVCView mStudentMVCViewInitializedInstance = (StudentMVCView) this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);

Во второй строке вы получаете фрагмент как супертип, который является типом фреймворка Android Fragment, в этом случае вы не можете получить доступ к этим дополнительным элементам в StudentMVCView type

  Fragment mStudentMVCViewFragmentInitializedInstance = this.getSupportFragmentManager().findFragmentById(R.id.mvc_view_fragment);
...