Android Open Source - MythTrack Item List






From Project

Back to project page MythTrack.

License

The source code is released under:

MIT License

If you think the Android project MythTrack listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 * ItemList is a fragment that displays a list of items of a certain type so that the user can add
 * them to their hero's inventory./*from  w w  w  .  j  a va  2 s.c  o  m*/
 *
 * @author Nolan Jurgens
 */

package nolanjurgens.mythtrack.app;

// IMPORTS /////////////////////////////////////////////////////////////////////////////////////////
import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import nolanjurgens.mythtrack.R;
import nolanjurgens.mythtrack.provider.MythTrackContract;

////////////////////////////////////////////////////////////////////////////////////////////////////
// CLASS - ItemList                                                                               //
////////////////////////////////////////////////////////////////////////////////////////////////////
public class ItemList extends ListFragment
  implements LoaderManager.LoaderCallbacks<Cursor>
{
  // FIELDS ////////////////////////////////////////////////////////////////////////////////////////

  /**  Object used to control a Contextual Action Bar*/
  protected ActionMode actionMode;
  /** An adapter used to display the inventory list.*/
  private SimpleCursorAdapter adapter;
  /** Helper for accessing/modifying the "Items" table.*/
  private ItemHelper items;
  /** Tracks which item in the list is selected.*/
  private int selectedItem = -1;

  // INTERFACES ////////////////////////////////////////////////////////////////////////////////////

  /** Interface for a listener for when an item is added to an inventory.*/
  OnItemAddedListener addedCallback;
  public interface OnItemAddedListener
  {
    public void onItemAdded(long heroID, long itemID);
  }

  // LISTENERS /////////////////////////////////////////////////////////////////////////////////////

  /** Contextual action mode click listener.*/
  AdapterView.OnItemClickListener contextualActionModeClickListener
    = new AdapterView.OnItemClickListener()
  {
    /**
     * Handle clicks in contextual action mode.
     * @param adapterView The hero list.
     * @param view The item that was clicked.
     * @param position The position of the clicked item in the list.
     * @param itemID The ID of the clicked item.
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long itemID)
    {
      // Save the position of the selected item.
      selectedItem = position;

      // Get the cursor entry for the selected item.
      Cursor cursor = adapter.getCursor();
      cursor.moveToPosition(selectedItem);

      // Set the item's name as the title.
      String itemName =
        cursor.getString(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME));
      actionMode.setTitle(itemName);
    }
  };


  /** Default item click listener.*/
  AdapterView.OnItemClickListener defaultClickListener = new AdapterView.OnItemClickListener()
  {
    /**
     * Default handling of list item clicks.
     * @param adapterView The hero list.
     * @param view The item that was clicked.
     * @param position The position of the clicked item in the list.
     * @param itemID The ID of the clicked item.
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long itemID)
    {
      // Save the position of the selected item.
      selectedItem = position;
      getListView().setItemChecked(selectedItem, true);

      // Check if action mode is already active.
      if(actionMode != null)
      {
        return;
      }

      // Enter contextual action mode.
      actionMode = getActivity().startActionMode(actionModeCallback);
      view.setSelected(true);
    }
  };


  /** Listener that brings up the contextual action bar on long click.*/
  AdapterView.OnItemLongClickListener defaultLongClickListener
    =  new AdapterView.OnItemLongClickListener()
  {
    /**
     * Brings up the contextual action bar on long clicks.
     * @param adapterView The hero list.
     * @param view The item that was clicked.
     * @param position The position of the clicked item in the list.
     * @param itemID The ID of the clicked item.
     * @return True if the long click was handled.
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long itemID)
    {
      // Save the position of the selected item.
      selectedItem = position;
      getListView().setItemChecked(selectedItem, true);

      // Check if action mode is already active.
      if(actionMode != null)
      {
        return false;
      }

      // Enter contextual action mode.
      actionMode = getActivity().startActionMode(actionModeCallback);
      view.setSelected(true);

      return true;
    }
  };

  // CONTEXTUAL ACTION MODE ////////////////////////////////////////////////////////////////////////

  /**
   * Defines the methods to handle a contextual action mode callback.
   */
  private ActionMode.Callback actionModeCallback = new ActionMode.Callback()
  {
    /**
     * Create the contextual action bar.
     * @param mode The contextual action mode object.
     * @param menu The contextual menu items.
     * @return Return true to create or false to abort.
     */
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu)
    {
      MenuInflater inflater = mode.getMenuInflater();
      inflater.inflate(R.menu.item_list_context, menu);

      return true;
    }


    /**
     * Called each time the contextual action bar is shown.
     * @param mode The contextual action mode object.
     * @param menu The contextual menu items.
     * @return Return true if the menu or action mode was updated or false if they weren't.
     */
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu)
    {
      // Disable long clicks while in contextual action mode.
      getListView().setOnItemLongClickListener(null);
      // Make single clicks change the selection.
      getListView().setOnItemClickListener(contextualActionModeClickListener);

      // Get the cursor entry for the selected item.
      Cursor cursor = adapter.getCursor();
      cursor.moveToPosition(selectedItem);

      // Set the item's name as the title.
      String itemName =
        cursor.getString(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME));
      mode.setTitle(itemName);

      return true;
    }


    /**
     * Handle the selected contextual action item.
     * @param mode The contextual action mode object.
     * @param item The item that was selected.
     * @return Returns true to signal item was processed or false if it should be passed on.
     */
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item)
    {
      switch(item.getItemId())
      {
        case R.id.action_get_item:
        {
          // Get the cursor entry for the selected item.
          Cursor cursor = adapter.getCursor();
          cursor.moveToPosition(selectedItem);

          // Get the heroID.
          long heroID = getArguments().getLong("hero_id");
          long itemID = cursor.getLong(cursor.getColumnIndex(MythTrackContract.Items._ID));

          // Add the item to the hero's inventory via the activity.
          addedCallback.onItemAdded(heroID, itemID);

          // Leave the action mode.
          mode.finish();
          return true;
        }
        case R.id.action_buy_item:
        {
          // Get the cursor entry for the selected item.
          Cursor cursor = adapter.getCursor();
          cursor.moveToPosition(selectedItem);

          // Build information bundle for dialog.
          Bundle arguments = getArguments();
          long itemID = cursor.getLong(cursor.getColumnIndex(MythTrackContract.Items._ID));

          Item purchaseItem = items.getItem(itemID);

          arguments.putLong("item_id", itemID);
          arguments.putString("item_name", purchaseItem.getName());
          arguments.putInt("item_cost", purchaseItem.getBuyCost());

          // Create dialog and pass arguments.
          DialogFragment buyItemDialog = new BuyItemDialog();
          buyItemDialog.setArguments(arguments);

          // Show the dialog.
          FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
          buyItemDialog.show(fragmentTransaction, "BuyItemDialog");

          // Leave the action mode.
          mode.finish();
          return true;
        }
        default:
        {
          return false;
        }
      }
    }


    /**
     * Called when contextual action mode is exited.
     * @param mode The contextual action mode object.
     */
    @Override
    public void onDestroyActionMode(ActionMode mode)
    {
      // Switch back to default click listeners.
      getListView().setOnItemClickListener(defaultClickListener);
      getListView().setOnItemLongClickListener(defaultLongClickListener);

      // Deselect the item.
      getListView().setItemChecked(selectedItem, false);
      selectedItem = -1;

      // Clear the action mode object.
      actionMode = null;
    }
  };

  // METHODS ///////////////////////////////////////////////////////////////////////////////////////

  /**
   * Called after the parent activity is created and the fragment is about to be activated.
   * @param savedInstanceState Saved instance information.
   */
  @Override
  public void onActivityCreated(Bundle savedInstanceState)
  {
    super.onActivityCreated(savedInstanceState);

    // Generate the item list and set the fragment to display it.
    adapter =  new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_activated_1,
      null, new String[]{MythTrackContract.Items.COLUMN_NAME},
      new int[]{android.R.id.text1}, 0);

    // Add rarity indicator to the item entries.
    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder()
    {
      /**
       * Set the item entries background based on the rarity of the item.
       * @param view The view being processed.
       * @param cursor The item list cursor.
       * @param columnIndex The column in the cursor which is being processed.
       * @return True if the data was bound into the view.
       */
      public boolean setViewValue(View view, Cursor cursor, int columnIndex)
      {
        // Get the column indices.
        int nameColumn = cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME);
        int rarityColumn = cursor.getColumnIndex(MythTrackContract.Items.COLUMN_RARITY);

        // Process the name column.
        if(columnIndex == nameColumn)
        {
          TextView textView = (TextView) view;

          // Set the background color base on item rarity.
          final int alpha = 35;
          switch(cursor.getInt(rarityColumn))
          {
            case MythTrackContract.Items.BROWN:
            {
              textView.setBackgroundColor(Color.argb(alpha, 120, 68, 33));
              break;
            }
            case MythTrackContract.Items.GREEN:
            {
              textView.setBackgroundColor(Color.argb(alpha, 0, 128, 0));
              break;
            }
            case MythTrackContract.Items.BLUE:
            {
              textView.setBackgroundColor(Color.argb(alpha, 0, 0, 200));
              break;
            }
            case MythTrackContract.Items.YELLOW:
            {
              textView.setBackgroundColor(Color.argb(alpha, 255, 221, 85));
              break;
            }
            case MythTrackContract.Items.ORANGE:
            {
              textView.setBackgroundColor(Color.argb(alpha, 255, 102, 0));
              break;
            }
            case MythTrackContract.Items.RED:
            {
              textView.setBackgroundColor(Color.argb(alpha, 170, 0, 0));
              break;
            }
            default:
            {
            }
          }
          textView.setText(cursor.getString(nameColumn));
          return true;
        }
        return false;
      }
    });

    // Set the list to use the adapter.
    setListAdapter(adapter);
    getLoaderManager().initLoader(R.id.herotracker_fragment_container, null, this);

    // Set up the click listeners.
    getListView().setOnItemClickListener(defaultClickListener);
    getListView().setOnItemLongClickListener(defaultLongClickListener);
  }


  /**
   * Called when the fragment is attached to the activity.
   * @param activity The host activity.
   */
  @Override
  public void onAttach(Activity activity)
  {
    super.onAttach(activity);

    // Make sure the host activity implements the interfaces.
    try
    {
      addedCallback = (OnItemAddedListener) activity;
    }
    catch(ClassCastException exception)
    {
      throw new ClassCastException(activity.toString() + " must implement onItemAdded");
    }
  }


  /**
   * Called when the fragment is first created.
   * @param savedInstanceState Saved instance information.
   */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    // Indicate that the fragment will add action bar items.
    setHasOptionsMenu(true);

    // Initialize the hero table helper.
    Context context = getActivity();
    items = new ItemHelper(context);
  }


  /**
   * Add fragment specific items to the action bar menu.
   *
   * @param menu     The menu items are being added to.
   * @param inflater The menu inflater used to create the new items from a menu resource file.
   */
  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
  {
    inflater.inflate(R.menu.item_list, menu);

    super.onCreateOptionsMenu(menu, inflater);
  }


  /**
   * Called when the loader is created.
   * @param id ID of the loader.
   * @param bundle A bundle of additional arguments.
   * @return The created loader.
   */
  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle bundle)
  {
    int itemType = getArguments().getInt("type");

    // Selection clause matches the type of the chosen category.
    String selection;
    if(itemType == MythTrackContract.Items.PRIMARY || itemType == MythTrackContract.Items.SECONDARY)
    {
      // Primary/Secondary should also show two-handed weapons.
      selection = MythTrackContract.Items.COLUMN_TYPE + " = " + itemType + " OR "
        + MythTrackContract.Items.COLUMN_TYPE + " = " + MythTrackContract.Items.TWO_HANDED;
    }
    else
    {
      selection = MythTrackContract.Items.COLUMN_TYPE + " = " + itemType;
    }

    return new CursorLoader(getActivity(), MythTrackContract.Items.CONTENT_URI,
      MythTrackContract.Items.PROJECTION_LIST, selection, null,
      MythTrackContract.Items.SORT_ORDER_RARITY);
  }


  /**
   * Called when the fragment is about to be drawn for the first time.
   * @param inflater The layout inflater.
   * @param container The parent fragment container.
   * @param savedInstanceState Saved instance information.
   * @return The created view.
   */
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    // Set the subtitle
    ActionBar actionBar = getActivity().getActionBar();
    if(actionBar != null)
    {
      getActivity().getActionBar().setSubtitle(R.string.itemlist_subtitle);
    }

    return inflater.inflate(R.layout.fragment_item_list, container, false);
  }


  /**
   * Called when the loader finishes loading the cursor.
   * @param cursorLoader The cursor loader.
   * @param cursor The cursor being loaded.
   */
  @Override
  public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor)
  {
    // Swap in the newly loaded cursor.
    adapter.swapCursor(cursor);
  }


  /**
   * Called when the cursor data is being released.
   * @param cursorLoader The cursor loader.
   */
  @Override
  public void onLoaderReset(Loader<Cursor> cursorLoader)
  {
    // Release the cursor that's about to be closed.
    adapter.swapCursor(null);
  }


  /**
   * Handle a selected action button.
   *
   * @param item The item that was selected.
   *
   * @return Returns true to signal item was processed or false if it should be passed on.
   */
  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    switch(item.getItemId())
    {
      default:
      {
        return super.onOptionsItemSelected(item);
      }
    }
  }


  /**
   * Called when the fragment is being removed or replaced.
   */
  @Override
  public void onPause()
  {
    super.onPause();

    // Close the contextual action bar if one is open.
    if(actionMode != null)
    {
      actionMode.finish();
    }
  }

}




Java Source Code List

nolanjurgens.mythtrack.app.BuyItemDialog.java
nolanjurgens.mythtrack.app.CreateHeroDialog.java
nolanjurgens.mythtrack.app.DeleteHeroDialog.java
nolanjurgens.mythtrack.app.EquipmentInfoDialog.java
nolanjurgens.mythtrack.app.HeroDisplayFragment.java
nolanjurgens.mythtrack.app.HeroHelper.java
nolanjurgens.mythtrack.app.HeroList.java
nolanjurgens.mythtrack.app.HeroTrackerActivity.java
nolanjurgens.mythtrack.app.Hero.java
nolanjurgens.mythtrack.app.InventoryList.java
nolanjurgens.mythtrack.app.ItemHelper.java
nolanjurgens.mythtrack.app.ItemList.java
nolanjurgens.mythtrack.app.Item.java
nolanjurgens.mythtrack.app.MainActivity.java
nolanjurgens.mythtrack.app.RemoveItemDialog.java
nolanjurgens.mythtrack.app.SettingsActivity.java
nolanjurgens.mythtrack.app.SettingsFragment.java
nolanjurgens.mythtrack.app.StatInfoDialog.java
nolanjurgens.mythtrack.app.StatPickerDialog.java
nolanjurgens.mythtrack.app.TitleHelper.java
nolanjurgens.mythtrack.app.Title.java
nolanjurgens.mythtrack.provider.MythTrackBackup.java
nolanjurgens.mythtrack.provider.MythTrackContract.java
nolanjurgens.mythtrack.provider.MythTrackDatabase.java