我有一个片段(ItemFragment),带有一堆EditText,一个微调器和一个日期选择器。用户输入将保存在SQL数据库中。然后,用户输入使用RecyclerView显示在列表片段(ListFragment)中。当用户单击列表中的项目时,它将转到ItemFragment并恢复用户输入。我在ItemFragment中添加了onSaveInstanceState。我对Android很陌生,所以请耐心等待。那么如何在RecylerView的onTouchEvent中恢复ItemFragment状态呢?
ItemFragment.java (不确定这是否是正确的方法?)
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("unit", unit);
outState.putString("date", date);
outState.putString("note", Note);
}
ListFragment.java
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
Item selectedItem = mItems.get(position);
//How do I restore ItemFragment here???
return true;
}
return false;
}
已编辑添加了Item.java和ItemFragment.java的完整代码
Item.java
public class Item {
private Long id;
private String title;
private String quantity;
private String unit;
private String date;
private String Note;
public String getNote() {
return Note;
}
public void setNote(String Note) {
this.Note = Note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static Item getItemfromCursor(Cursor cursor){
Item item = new Item();
item.setId(cursor.getLong(cursor.getColumnIndex(Constants.COLUMN_ID)));
item.setTitle(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_TITLE)));
item.setQuantity(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_QUANTITY)));
item.setUnit(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_UNIT)));
item.setNote(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_NOTE)));
item.setDate(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_DATE)));
return item;
}
}
ItemFragment.java
public class ItemFragment extends DialogFragment {
private View mRootView;
private Item currentItem = null;
private Toolbar mToolbar;
private String date;
private String Note;
private String title;
private String quantity;
private TextView dateText;
private TextView unitError;
private EditText itemEditText;
private EditText quantityEditText;
private EditText noteEditText;
private Spinner remSpinner;
private Spinner spinner;
private String unit;
private String reminder;
private int spinnerCount=0;
private int spinnerInitializedCount=0;
private int remSpinnerCount=0;
private int remSpinnerInitializedCount=0;
public ItemFragment() {
}
//create an instance of the fragment
public static ItemFragment newInstance(long id) {
ItemFragment fragment = new ItemFragment();
if (id > 0) {
Bundle bundle = new Bundle();
bundle.putLong("id", id);
fragment.setArguments(bundle);
}
return fragment;
}
//get id of an item
public void getCurrentItem() {
Bundle args = getArguments();
if (args != null && args.containsKey("id")) {
long id = args.getLong("id", 0);
if (id > 0) {
currentItem = ItemManager.newInstance(getActivity()).getItem(id);
}
}
}
//notify Activity that the fragment wants to place an item in the menu
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getCurrentItem();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add_item, container, false);
itemEditText=(EditText)mRootView.findViewById((R.id.add_item));
quantityEditText=(EditText)mRootView.findViewById(R.id.amount);
unitError = (TextView)mRootView.findViewById(R.id.unit_error);
noteEditText = (EditText)mRootView.findViewById(R.id.add_notes);
dateText = (TextView)mRootView.findViewById(R.id.date_selected);
//unit spinner code here
//reminder spinner here
spinner.setOnItemSelectedListener(spinnerListener);
remSpinner.setOnItemSelectedListener(spinnerListener);
spinnerCount=1;
remSpinnerCount=1;
return mRootView;
}
//spinner listener
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
if(spinnerInitializedCount<spinnerCount){
spinnerInitializedCount++;
} else {
//get selected unit
unit = parent.getItemAtPosition(position).toString();
}
break;
case R.id.reminder_list:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
//get selected reminder
reminder = parent.getItemAtPosition(position).toString();
break;
}
}}
public void onNothingSelected(AdapterView<?> parent) {
}
};
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_item, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.delete:
if(currentItem != null){
promptForDelete();
}
else{
makeToast("Cannot delete item that has not been saved");
}
break;
case R.id.save:
if(saveItem()){
makeToast(currentItem != null ? "Item updated" : "Item saved");
}
break;
}
return super.onOptionsItemSelected(item);
}
private void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private boolean saveItem(){
Note = noteEditText.getText().toString();
date = dateText.getText().toString();
title = itemEditText.getText().toString();
if(TextUtils.isEmpty(title)){
itemEditText.setError("Item is required");
return false;
}
quantity = quantityEditText.getText().toString();
if(TextUtils.isEmpty(quantity)){
quantityEditText.setError("Quantity is required");
return false;
}
if(unit.equals("None")){
unitError = (TextView)spinner.getSelectedView();
unitError.setError("");
unitError.setTextColor(Color.RED);
unitError.setTextSize(R.dimen.text_size_normal);
unitError.setText("Select a unit!");
return false;
}
if(currentItem != null){
currentItem.setTitle(title);
currentItem.setQuantity(quantity);
currentItem.setUnit(unit);
currentItem.setDate(date);
currentItem.setNote(Note);
ItemManager.newInstance(getActivity()).update(currentItem);
}
else {
Item item = new Item();
item.setTitle(title);
item.setQuantity(quantity);
item.setUnit(unit);
item.setDate(date);
item.setNote(Note);
ItemManager.newInstance(getActivity()).create(item);
}
return true;
}
private void populateFields(){
itemEditText.setText(currentItem.getTitle());
quantityEditText.setText(currentItem.getQuantity());
noteEditText.setText(currentItem.getNote());
dateText.setText(currentItem.getDate());
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("selunit", unit);
outState.putString("seldate", date);
outState.putString("note", Note);
}
public void promptForDelete(){
final String itemToBeDeleted = currentItem.getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete" + itemToBeDeleted + "?");
alertDialog.setMessage("Are you sure you want to delete " + itemToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ItemManager.newInstance(getActivity()).delete(currentItem);
makeToast(itemToBeDeleted + "deleted");
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
已编辑 - 添加了ItemListAdapter.java&amp; ItemManager.java
ItemListAdapter.java
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder> {
private List<Item> mItems;
private Context mContext;
public ItemListAdapter(List<Item> items, Context context){
mItems = items;
mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(rowView);
return viewHolder;
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemx.setText(mItems.get(position).getTitle());
holder.quantity.setText(String.valueOf(mItems.get(position).getQuantity()));
holder.unit.setText(mItems.get(position).getUnit());
holder.note.setText(mItems.get(position).getNote());
holder.expDate.setText(mItems.get(position).getDate());
}
@Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView itemx;
public final TextView quantity;
public final TextView unit;
public final TextView note;
public final TextView expDate;
public ViewHolder(View itemView) {
super(itemView);
itemx = (TextView)itemView.findViewById(R.id.tv_item);
quantity = (TextView)itemView.findViewById(R.id.tv_quantity);
unit = (TextView)itemView.findViewById(R.id.tv_unit);
note = (TextView)itemView.findViewById(R.id.tv_note);
expDate = (TextView)itemView.findViewById(R.id.tv_exp_date);
}
}
public void promptForDelete(final int position){
String fieldToBeDeleted = mItems.get(position).getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Delete " + fieldToBeDeleted + " ?");
alertDialog.setMessage("Are you sure you want to delete the item " + fieldToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mItems.remove(position);
notifyItemRemoved(position);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
ItemManager.java
public class ItemManager{
private Context mContext;
private static ItemManager itemManagerInstance = null;
public static ItemManager newInstance(Context context){
if (itemManagerInstance == null){
itemManagerInstance = new ItemManager(context.getApplicationContext());
}
return itemManagerInstance;
}
private ItemManager(Context context){
this.mContext = context.getApplicationContext();
}
public long create(Item item){
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_TITLE, item.getTitle());
values.put(Constants.COLUMN_QUANTITY, item.getQuantity());
values.put(Constants.COLUMN_UNIT, item.getUnit());
values.put(Constants.COLUMN_EXPIRY_DATE, item.getDate());
values.put(Constants.COLUMN_NOTE, item.getNote());
Uri result = mContext.getContentResolver().insert(XContentProvider.ITEM_URI, values);
long id = Long.parseLong(result.getLastPathSegment());
return id;
}
public void update(Item item){
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_TITLE, item.getTitle());
values.put(Constants.COLUMN_QUANTITY, item.getQuantity());
values.put(Constants.COLUMN_UNIT, item.getUnit());
values.put(Constants.COLUMN_EXPIRY_DATE, item.getDate());
values.put(Constants.COLUMN_NOTE, item.getNote());
mContext.getContentResolver().update(XContentProvider.ITEM_URI, values, Constants.COLUMN_ID + " = " + item.getId(), null);
}
public void delete(Item item){
mContext.getContentResolver().delete(XContentProvider.ITEM_URI, Constants.COLUMN_ID + " = " + item.getId(), null);
}
public List<Item> getAllItems(){
List<Item> items = new ArrayList<Item>();
Cursor cursor = mContext.getContentResolver().query(XContentProvider.ITEM_URI, Constants.COLUMNS, null, null, null);
if (cursor != null){
cursor.moveToFirst();
while (!cursor.isAfterLast()){
items.add(Item.getItemfromCursor(cursor));
cursor.moveToNext();
}
cursor.close();
}
return items;
}
public Item getItem(Long id){
Item item;
Cursor cursor = mContext.getContentResolver().query(XContentProvider.ITEM_URI, Constants.COLUMNS, Constants.COLUMN_ID + " = " + id, null, null);
if (cursor != null){
cursor.moveToFirst();
item = Item.getItemfromCursor(cursor);
return item;
}
return null;
}
}
答案 0 :(得分:0)
您可能需要使用SharedPreferences
或SQL database
来保存数据。onSaveInstanceState
用于在片段可能被销毁时保存状态。
只需将项目ID传递给ItemFragment
并在其中显示数据。
openFragment(new ItemFragment(item.getId()), "Add Item")
package com.airi.vcare;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class ItemFragment extends DialogFragment {
private View mRootView;
private Item currentItem = null;
private Toolbar mToolbar;
private String date;
private String Note;
private String title;
private String quantity;
private TextView dateText;
private TextView unitError;
private EditText itemEditText;
private EditText quantityEditText;
private EditText noteEditText;
private Spinner remSpinner;
private Spinner spinner;
private String unit;
private String reminder;
private int spinnerCount=0;
private int spinnerInitializedCount=0;
private int remSpinnerCount=0;
private int remSpinnerInitializedCount=0;
public ItemFragment() {
}
//create an instance of the fragment
public static ItemFragment newInstance(long id) {
ItemFragment fragment = new ItemFragment();
if (id > 0) {
Bundle bundle = new Bundle();
bundle.putLong("id", id);
fragment.setArguments(bundle);
}
return fragment;
}
//get id of an item
public void getCurrentItem() {
Bundle args = getArguments();
if (args != null && args.containsKey("id")) {
long id = args.getLong("id", 0);
if (id > 0) {
currentItem = ItemManager.newInstance(getActivity()).getItem(id);
}
}
}
//notify Activity that the fragment wants to place an item in the menu
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getCurrentItem();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add_item, container, false);
itemEditText=(EditText)mRootView.findViewById((R.id.add_item));
quantityEditText=(EditText)mRootView.findViewById(R.id.amount);
unitError = (TextView)mRootView.findViewById(R.id.unit_error);
noteEditText = (EditText)mRootView.findViewById(R.id.add_notes);
dateText = (TextView)mRootView.findViewById(R.id.date_selected);
//unit spinner code here
//reminder spinner here
spinner.setOnItemSelectedListener(spinnerListener);
remSpinner.setOnItemSelectedListener(spinnerListener);
spinnerCount=1;
remSpinnerCount=1;
//just display fields .
populateFields();
return mRootView;
}
//spinner listener
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
if(spinnerInitializedCount<spinnerCount){
spinnerInitializedCount++;
} else {
//get selected unit
unit = parent.getItemAtPosition(position).toString();
}
break;
case R.id.reminder_list:
//set spinner text appearance
((TextView)parent.getChildAt(0)).setTextSize(13);
((TextView)parent.getChildAt(0)).setTextColor(Color.DKGRAY);
//get selected reminder
reminder = parent.getItemAtPosition(position).toString();
break;
}
}}
public void onNothingSelected(AdapterView<?> parent) {
}
};
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_item, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.delete:
if(currentItem != null){
promptForDelete();
}
else{
makeToast("Cannot delete item that has not been saved");
}
break;
case R.id.save:
if(saveItem()){
makeToast(currentItem != null ? "Item updated" : "Item saved");
}
break;
}
return super.onOptionsItemSelected(item);
}
private void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private boolean saveItem(){
Note = noteEditText.getText().toString();
date = dateText.getText().toString();
title = itemEditText.getText().toString();
if(TextUtils.isEmpty(title)){
itemEditText.setError("Item is required");
return false;
}
quantity = quantityEditText.getText().toString();
if(TextUtils.isEmpty(quantity)){
quantityEditText.setError("Quantity is required");
return false;
}
if(unit.equals("None")){
unitError = (TextView)spinner.getSelectedView();
unitError.setError("");
unitError.setTextColor(Color.RED);
unitError.setTextSize(R.dimen.text_size_normal);
unitError.setText("Select a unit!");
return false;
}
if(currentItem != null){
currentItem.setTitle(title);
currentItem.setQuantity(quantity);
currentItem.setUnit(unit);
currentItem.setDate(date);
currentItem.setNote(Note);
ItemManager.newInstance(getActivity()).update(currentItem);
}
else {
Item item = new Item();
item.setTitle(title);
item.setQuantity(quantity);
item.setUnit(unit);
item.setDate(date);
item.setNote(Note);
ItemManager.newInstance(getActivity()).create(item);
}
return true;
}
private void populateFields(){
itemEditText.setText(currentItem.getTitle());
quantityEditText.setText(currentItem.getQuantity());
noteEditText.setText(currentItem.getNote());
dateText.setText(currentItem.getDate());
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("title", title);
outState.putString("quantity", quantity);
outState.putString("selunit", unit);
outState.putString("seldate", date);
outState.putString("note", Note);
}
public void promptForDelete(){
final String itemToBeDeleted = currentItem.getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete" + itemToBeDeleted + "?");
alertDialog.setMessage("Are you sure you want to delete " + itemToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ItemManager.newInstance(getActivity()).delete(currentItem);
makeToast(itemToBeDeleted + "deleted");
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder> {
private List<Item> mItems;
private Context mContext;
public ItemListAdapter(List<Item> items, Context context){
mItems = items;
mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(rowView);
return viewHolder;
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemx.setText(mItems.get(position).getTitle());
holder.quantity.setText(String.valueOf(mItems.get(position).getQuantity()));
holder.unit.setText(mItems.get(position).getUnit());
holder.note.setText(mItems.get(position).getNote());
holder.expDate.setText(mItems.get(position).getDate());
holder.item.getParent().setOnClick(new OnClickListener(){
onclick(View view){
//todo here
openFragment(new ItemFragment(item.getId()), "Add Item")
}
})
}
@Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView itemx;
public final TextView quantity;
public final TextView unit;
public final TextView note;
public final TextView expDate;
public ViewHolder(View itemView) {
super(itemView);
itemx = (TextView)itemView.findViewById(R.id.tv_item);
quantity = (TextView)itemView.findViewById(R.id.tv_quantity);
unit = (TextView)itemView.findViewById(R.id.tv_unit);
note = (TextView)itemView.findViewById(R.id.tv_note);
expDate = (TextView)itemView.findViewById(R.id.tv_exp_date);
}
}
public void promptForDelete(final int position){
String fieldToBeDeleted = mItems.get(position).getTitle();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Delete " + fieldToBeDeleted + " ?");
alertDialog.setMessage("Are you sure you want to delete the item " + fieldToBeDeleted + "?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mItems.remove(position);
notifyItemRemoved(position);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}