How to insert an event into the Navigation Drawer menu item?

Asked

Viewed 1,068 times

0

How to insert an event into the Navigation Drawer menu item? I was only able to do it using the option menus other than Nav. Drawer.

Loginactivity.java

package com.androidbegin.parselogintutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
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.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import br.isckosta.sharingfuel.adapter.ListViewAdapter;
import br.isckosta.sharingfuel.model.Posto;

import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.PushService;

public class FeedActivityNavigationDrawer extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;

ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapter adapter;
private List<Posto> posto = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome);

    ParseAnalytics.trackAppOpened(getIntent());

    PushService.setDefaultPushCallback(this,
            FeedActivityNavigationDrawer.class);

    mTitle = mDrawerTitle = getTitle();
    mPlanetTitles = getResources().getStringArray(R.array.planets_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
            GravityCompat.START);
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
    mDrawerLayout, /* DrawerLayout object */
    R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
    R.string.drawer_open, /* "open drawer" description for accessibility */
    R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to
                                        // onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to
                                        // onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    switch (item.getItemId()) {
    case R.id.action_websearch:

        return true;
    case R.id.add_new_post:

        return true;
    case R.id.sair:

        ParseUser.logOut();
        finish();

        Intent i = new Intent(FeedActivityNavigationDrawer.this,
                LoginSignupActivity.class);
        startActivity(i);

        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(
                FeedActivityNavigationDrawer.this);
        mProgressDialog.setTitle("Carregando novos preços");
        mProgressDialog.setMessage("Atualizando...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        posto = new ArrayList<Posto>();
        try {
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                    "Posto");
            query.orderByAscending("ranknum");
            ob = query.find();
            for (ParseObject country : ob) {
                ParseFile image = (ParseFile) country.get("flag");

                Posto map = new Posto();
                map.setNome((String) country.get("nome"));
                map.setBandeira((String) country.get("bandeira"));
                map.setEndereco((String) country.get("endereco"));
                map.setFlag(image.getUrl());
                posto.add(map);
            }
        } catch (ParseException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        listview = (ListView) findViewById(R.id.listview);
        adapter = new ListViewAdapter(FeedActivityNavigationDrawer.this,
                posto);
        listview.setAdapter(adapter);
        mProgressDialog.dismiss();
    }
}

private class DrawerItemClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {
    Fragment fragment = new PlanetFragment();
    Bundle args = new Bundle();
    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
    fragment.setArguments(args);

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.content_frame, fragment).commit();

    mDrawerList.setItemChecked(position, true);
    setTitle(mPlanetTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

public static class PlanetFragment extends Fragment {
    public static final String ARG_PLANET_NUMBER = "planet_number";

    public PlanetFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_planet,
                container, false);
        int i = getArguments().getInt(ARG_PLANET_NUMBER);
        String planet = getResources()
                .getStringArray(R.array.planets_array)[i];

        int imageId = getResources().getIdentifier(
                planet.toLowerCase(Locale.getDefault()), "drawable",
                getActivity().getPackageName());
        ((ImageView) rootView.findViewById(R.id.image))
                .setImageResource(imageId);
        getActivity().setTitle(planet);
        return rootView;
    }
}

}

I entered this code in selectedItem() but it always executes one of these cases when opening Activity

  switch (position) {

    case 0:

        Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT)
                .show();
        break;


    case 1:

        Toast.makeText(getApplicationContext(), "Criar novo preço", Toast.LENGTH_SHORT)
                .show();
        break;

    case 2:

        Toast.makeText(getApplicationContext(), "Sobre",
                Toast.LENGTH_SHORT).show();
        break;
    case 3:

        ParseUser.logOut();
        finish();

        Intent i = new Intent(FeedActivityNavigationDrawer.this,
                LoginSignupActivity.class);
        startActivity(i);
        break;

    default:
        break;
    }
  • By your code, you are opening only the PlanetFragment passing the selected item in question. Everything happens in your method selectItem(). What exactly or what event you plan to do?

  • I’ll edit the question @Paulorodrigues

2 answers

2

You must implement the Drawer system by inserting the chord below:

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        selectItem(position);
    }
}

/** Swaps fragments in the main content view */
private void selectItem(int position) {
    // Create a new fragment and specify the planet to show based on position
    Fragment fragment = new PlanetFragment();
    Bundle args = new Bundle();
    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
    fragment.setArguments(args);

    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
                   .replace(R.id.content_frame, fragment)
                   .commit();

    // Highlight the selected item, update the title, and close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mPlanetTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}
  • How to do in case of event without opening a Fragment? Type has a Logout button.

  • 1

    In the selectItem() method, if the selected position is the Logout option, then you make a call to the Logout function.

  • I did using the switch look at the question.

  • I managed to do, but now whenever you open Activity the first Home menu runs.

  • 1

    Maybe the home option is at position 0

  • I saw before you post your comment rsrs... Thank you so much @Daniel Reis

Show 1 more comment

0

Now that I have seen personal, in the onCreate() method is being called the method

if (savedInstanceState == null) {
        selectItem(0);
}

In which already creates the Activity selecting the first position, I missed to observe it. Thanks for all your help.

I have to leave, because whenever the Activity is opened, it will call the first position that means the position of the first Fragment that is the Feed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.