如何在按下后退按钮时刷新片段?

时间:2015-07-24 05:47:25

标签: android listview

当按下后退按钮时,如何刷新片段的视图?

我在片段的onResume方法中尝试了这个,但它没有用。

好的,这是代码

@SuppressWarnings("unused")
public class RestaurantMenuFragment extends Fragment {

    private static final String TAG = "MenuItemsFragment";
    private static final String CATEGORIES_KEY = "categories";
    private static final String SELECTED_CATEGORY_ID_KEY = "category";
    private static final String RESTAURANT_KEY = "restaurant123";
    private static final String RESTAURANT_KCITY = "city";
    private Spinner mCategoriesSpinner;
    private ArrayAdapter<CategoriesResponse.Category> mCategoriesAdapter;
    private ListView mListView;
    private List<MenuItem> mItems;
    private MenuItemsAdapter mItemsAdapter;
    private EmptyLayout mEmptyLayout;
    private Restaurant mRestaurant;
    private int mCategoryId;
    private List<CategoriesResponse.Category> mCategories;
    private RestaurantActivity mActivity;
    private MainApplication mApplication;
    private CategoriesResponse mCategoriesResponse;
    private ActionBar mActionBar;
    private Gson mGson;
    int categ;
    private ObjectGetter mObjectGetter;

    public static RestaurantMenuFragment newInstance(Restaurant restaurant) {
        RestaurantMenuFragment fragment = new RestaurantMenuFragment();
        Bundle args = new Bundle();
        args.putString(RESTAURANT_KEY, new Gson().toJson(restaurant));
         String dd=restaurant.city;

         Log.i("dd12", dd);
        fragment.setArguments(args);

        return fragment;
    }

    public RestaurantMenuFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivity = (RestaurantActivity) getActivity();
        mApplication = (MainApplication) mActivity.getApplication();
        mActionBar = mActivity.getSupportActionBar();

        mGson = new Gson();

        mObjectGetter = new ObjectGetter();
        mCategories = new ArrayList<CategoriesResponse.Category>();
        Log.i("mCategories",""+mCategories);
        mItems = new ArrayList<MenuItem>();
        Log.i("12345",""+mItems);
        mItemsAdapter = new MenuItemsAdapter(getActivity(), mItems);    

        Bundle args = getArguments();
        if (args != null) {
            mRestaurant = mGson.fromJson(args.getString(RESTAURANT_KEY),
                    Restaurant.class);
        }

        if (savedInstanceState != null) {
            mRestaurant = mGson.fromJson(
                    savedInstanceState.getString(RESTAURANT_KEY),
                    Restaurant.class);
            mCategoryId = savedInstanceState.getInt(SELECTED_CATEGORY_ID_KEY);
            mCategoriesResponse = mGson.fromJson(
                    savedInstanceState.getString(CATEGORIES_KEY),
                    CategoriesResponse.class);
        }

        assert mRestaurant != null;    
        updateCart();
    }

    public void updateCart() {
        View view = mActionBar.getCustomView();
        Button cartButton = (Button) view.findViewById(R.id.cartButton);

        int nOfItems = 0;
        if (mApplication.isCartCreated()) {
            nOfItems = mApplication.getCart().getNOfAllItems();
        }
        cartButton.setText(String.format("%d", nOfItems));
        if (nOfItems > 0) {
            cartButton.setEnabled(true);
        } else {
            cartButton.setEnabled(false);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Gson gson = new Gson();

        outState.putString(RESTAURANT_KEY, gson.toJson(mRestaurant));
        outState.putInt(SELECTED_CATEGORY_ID_KEY, mCategoryId);
        outState.putString(CATEGORIES_KEY, gson.toJson(mCategoriesResponse));
    }   

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub    
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.spinner_list, container, false);
       RestaurantActivity activity = (RestaurantActivity) getActivity();
       String myDataFromActivity = activity.getMyData();
       String myDataFromActivity1 = activity.getMyData1();
       Log.i("myDataFromActivity",myDataFromActivity);
       Log.i("myDataFromActivity1",myDataFromActivity1);

       categ=Integer.parseInt(myDataFromActivity1);

        mListView = (ListView) view.findViewById(R.id.list122334);
        mListView.setAdapter(mItemsAdapter);

        Log.d(TAG,"Querying items url "
                + Urls.menuItemsQuery(mRestaurant.id,categ));       

        mEmptyLayout = EmptyLayout.with(getActivity()).to(mListView)
                .setEmptyMessage(R.string.categories_empty_message)
                .showLoading();                 

        loadItems();
        return view;
    }

    private void loadItems() {
        mEmptyLayout.showLoading();
        mItems.clear();
        mObjectGetter.getJsonObjectOrDialog(mActivity,
                Urls.menuItemsQuery(mRestaurant.id, categ),
                ItemsResponse.class,
                new ObjectGetter.OnFinishedListener<ItemsResponse>() {
                    @Override
                    public void onFinishedLoadingObject(
                            ItemsResponse itemsResponse) {
                        mEmptyLayout.showEmpty();

                        if (itemsResponse != null
                                && itemsResponse.items != null) {
                            mItems.addAll(itemsResponse.items);
                        }
                        mItemsAdapter.notifyDataSetChanged();

                    }
                });
        }


    private class MenuItemsAdapter extends ArrayAdapter<MenuItem> {

        private static final String TAG = "MenuItemsAdapter";

        public MenuItemsAdapter(Context context, List<MenuItem> menuItems) {
            super(context, 0, menuItems);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final MenuItem menuItem = getItem(position);                

            View view = convertView;
            final ViewHolder viewHolder;
            LayoutInflater inflater;
            if (convertView == null) {
                inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.menu_item, parent, false);
                viewHolder = new ViewHolder();

                viewHolder.name = (TextView) view.findViewById(R.id.name);
                viewHolder.description = (TextView) view.findViewById(R.id.description);
                viewHolder.price = (TextView) view.findViewById(R.id.price);
                viewHolder.add = (Button) view.findViewById(R.id.add);
                viewHolder.selectedView = view.findViewById(R.id.selectedView);
                viewHolder.remove = (Button) view.findViewById(R.id.remove);
                viewHolder.total = (TextView) view.findViewById(R.id.itemTotal);
                viewHolder.quantity = (TextView) view.findViewById(R.id.quantity);

                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            try
            {               
                viewHolder.name.setText(menuItem.name);
                viewHolder.description.setText(menuItem.description);

                viewHolder.price.setText(String.valueOf(menuItem.price));

            }catch(NullPointerException e){
                 e.printStackTrace();
            }

            viewHolder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {                   

                    mApplication.createNewCartIfPossibleAndAskIfNot(
                            getActivity(), mRestaurant,
                            new MainApplication.OnCreateCartListener() {
                                @Override
                                public void onCreateCart(Cart cart) {
                                    cart.addOne(menuItem);
                                    updateItemFromCart(menuItem, viewHolder);
                                    updateCart();
                                }
                            });
                }
            });

            viewHolder.remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (!mApplication.isCartCreated()) {
                        return;
                    }
                    mApplication.getCart().removeOne(menuItem);
                    updateItemFromCart(menuItem, viewHolder);
                    updateCart();
                }
            });   

            return view;
        }

        private void updateItemFromCart(MenuItem menuItem, ViewHolder viewHolder) {    
            if (!mApplication.isCartCreated()) {
                return;
            }
            int quantity = mApplication.getCart().getNOfItemsOfType(menuItem);
            if (quantity > 0) {
                viewHolder.selectedView.setVisibility(View.VISIBLE);
            } else {
                viewHolder.selectedView.setVisibility(View.GONE);
            }
            viewHolder.quantity.setText(String.valueOf(quantity));

            viewHolder.total.setText(String.valueOf(quantity
                    * menuItem.price));
        }

        class ViewHolder {
            TextView name;
            TextView description;
            TextView price;
            Button add;
            View selectedView;
            Button remove;
            TextView total;
            TextView quantity;              
        }    
    }

    @Override
    public void onResume() {
        super.onResume();

        updateCart();
        mItems.clear();
        if (mItemsAdapter != null) {

            mItemsAdapter.notifyDataSetChanged();               
        }   
    }

    @Override
    public void onDestroy() {
        if (mObjectGetter != null) {
            mObjectGetter.stopRequests();
        }
        super.onDestroy();      
    }
}

现在,我想在用户按下后退按钮时更新listvieww数据。我在片段的onResume()方法中设置了新的loadItems()方法。调用此方法但会显示旧的列表视图数据,并且还会显示新数据......

5 个答案:

答案 0 :(得分:3)

后退按钮应该从Activity处理。 您可以在Activity中覆盖onBackPressed并将相应片段上的函数调用到reloadItems()。

以下是我能想到的3个选项。

  1. 获取对Fragment的引用并将函数调用到reLoadItems,最好为片段实现的通信定义接口。

  2. 比第一个更好的解决方案。添加一个LocalBroadcast,Activity播放,你的片段在接收广播时监听和更新数据。

  3. 示例: http://luboganev.github.io/blog/messaging-with-localbroadcastmanager/

    1. Otto事件总线,其中活动和片段类都连接到事件总线,并且它们活动发布事件和片段订阅它。这就是我在我的应用程序中使用类似的东西。 (但是我经常发生异步事件。所以我正在使用它。在你的情况下,第二个选项可能就足够了。)
    2. 示例: http://www.vogella.com/tutorials/JavaLibrary-EventBusOtto/article.html

答案 1 :(得分:0)

正如ramesh已经提到的,后退按钮处理发生在包含片段的活动类中。这是一个简单的示例,您可以如何处理片段的这些后退按钮事件。

活动代码:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  boolean returnSuperKeyDown = true;

  if(keyCode == KeyEvent.KEYCODE_BACK){
    Fragment fragment = getYourCurrentFragment();

    if (fragment instanceof YourFragment) {
      returnSuperKeyDown = ((YourFragment) fragment).onFragmentKeyDown();
    }
  }

  if (returnSuperKeyDown) {
    return super.onKeyDown(keyCode, event);
  } else {
    return true;
  }
}

YourFragment Method:

public boolean onFragmentKeyDown() {
  updateYourFragment();
  return false;
}

答案 2 :(得分:0)

@Rithe,@ sunder sharma

根据我的说法,当从其他片段返回时,很容易刷新片段,

我们只需要覆盖刷新片段的onActivityCreated方法。

喜欢

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
   //your code which you want to refresh
    loadItems();
}

答案 3 :(得分:0)

您还可以使用onStart()方法更新/刷新片段。

public void onStart(){


 super.onStart();
    //update your fragment
}

这对我来说很好。

答案 4 :(得分:-1)

调用你的loadItem()方法onHiddenChanged(boolean hidden)method.onHiddenChanged是覆盖方法