[英]How can I save the 'creating of a new instance of a fragment' in a variable?
[英]Android - How do I use the same fragment for editing and creating a new instance of my model?
我一直在尋找這個答案,但根本找不到答案。 它可能太具體了。 這是一個todoApp,我仍在將活動邏輯遷移到片段中。
TodoListActivity.java(在此調用TodoActivity的片段)
// ...
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Todo todo = new Todo();
TodoSingleton.get(TodoListActivity.this).addTodo(todo);
Intent i = TodoActivity.newIntent(TodoListActivity.this, todo.getId());
startActivity(i);
}
});
// ...
TodoFragment.java
//...
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.todo_fragment, container, false);
todoTitleEditText = (EditText) view.findViewById(R.id.todo_title_ed);
if(mTodo.getmTitle() != null) {
todoTitleEditText.setText(mTodo.getmTitle());
}
todoDescriptioneEditText = (EditText) view.findViewById(R.id.todo_description_ed);
if(mTodo.getmDescription() != null) {
todoDescriptioneEditText.setText(mTodo.getmDescription());
}
return view;
}
//...
題
我覺得這些if陳述不是正確的方法。 那么,我將如何使用相同的片段來創建新的模型實例和進行編輯?
讓我知道是否還不夠清楚。
謝謝
您需要至少區分同一類的片段之間的任何區別。
將此方法添加為片段(根據您的需要進行更改):
public class ActivitiesFragment extends Fragment{
private int mFragmentType;
public ActivitiesFragment(){
}
public static ActivitiesFragment getInstance(int pageNumber){
Bundle args = new Bundle();
args.putInt("type", pageNumber);
ActivitiesFragment fragment = new ActivitiesFragment();
fragment.setArguments(args);
fragment.mFragmentType = pageNumber;
return fragment;
}
}
現在您可以得到兩個不同的片段:
ActivitiesFragment fragmentOne = ActivitiesFragment.getInstance(1);
ActivitiesFragment fragmentTwo = ActivitiesFragment.getInstance(2);
//...
如果要對新模型實例使用相同的片段,則可以執行以下操作:
public class TodoFragmentFactory {
private TodoFragment mFragment;
private TodoFragment(){
}
public static TodoFragment getInstance(Todo todo){
if(mFragment==null){
mFragment = new TodoFragment();
}
mFragment.setTodo(todo);
return mFragment;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.