Example usage for android.view MenuItem setChecked

List of usage examples for android.view MenuItem setChecked

Introduction

In this page you can find the example usage for android.view MenuItem setChecked.

Prototype

public MenuItem setChecked(boolean checked);

Source Link

Document

Control whether this item is shown with a check mark.

Usage

From source file:email.schaal.ocreader.ListActivity.java

private void showSortPopup(View view) {
    PopupMenu popupMenu = new PopupMenu(this, view);
    popupMenu.inflate(R.menu.menu_sort);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    Sort order = Preferences.ORDER.getOrder(sharedPreferences);
    String field = Preferences.SORT_FIELD.getString(sharedPreferences);

    final MenuItem orderMenuItem = popupMenu.getMenu().findItem(R.id.action_sort_order);
    orderMenuItem.setChecked(order != Sort.ASCENDING);

    final MenuItem selectedField;

    if (field.equals(Item.PUB_DATE)) {
        selectedField = popupMenu.getMenu().findItem(R.id.action_sort_pubdate);
    } else {//from   w w  w .  ja v a 2 s.  c  o m
        selectedField = popupMenu.getMenu().findItem(R.id.action_sort_updatedate);
    }
    selectedField.setChecked(true);

    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            boolean updateSort = false;

            switch (item.getItemId()) {
            case R.id.action_sort_order:
                item.setChecked(!item.isChecked());
                sharedPreferences.edit().putBoolean(Preferences.ORDER.getKey(), !item.isChecked()).apply();
                updateSort = true;
                break;
            case R.id.action_sort_pubdate:
                sharedPreferences.edit().putString(Preferences.SORT_FIELD.getKey(), Item.PUB_DATE).apply();
                updateSort = true;
                break;
            case R.id.action_sort_updatedate:
                sharedPreferences.edit().putString(Preferences.SORT_FIELD.getKey(), Item.UPDATED_AT).apply();
                updateSort = true;
                break;
            }

            if (updateSort) {
                adapter.setOrder(Preferences.ORDER.getOrder(sharedPreferences),
                        Preferences.SORT_FIELD.getString(sharedPreferences));
            }
            return updateSort;
        }
    });

    popupMenu.show();
}

From source file:com.chni.lidong.androidtestdemo.swiperefreshlistfragment.SwipeRefreshListFragmentFragment.java

/**
 * Respond to the user's selection of the Refresh action item. Start the SwipeRefreshLayout
 * progress bar, then initiate the background task that refreshes the content.
 *
 * <p>A color scheme menu item used for demonstrating the use of SwipeRefreshLayout's color
 * scheme functionality. This kind of menu item should not be incorporated into your app,
 * it just to demonstrate the use of color. Instead you should choose a color scheme based
 * off of your application's branding.// w  w w  .j a  va2s . c  om
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_refresh:
        Log.i(LOG_TAG, "Refresh menu item selected");

        // We make sure that the SwipeRefreshLayout is displaying it's refreshing indicator
        if (!isRefreshing()) {
            setRefreshing(true);
        }

        // Start our refresh background task
        initiateRefresh();
        return true;

    case R.id.menu_color_scheme_1:
        Log.i(LOG_TAG, "setColorScheme #1");
        item.setChecked(true);

        // Change the colors displayed by the SwipeRefreshLayout by providing it with 4
        // color resource ids
        setColorScheme(R.color.color_scheme_1_1, R.color.color_scheme_1_2, R.color.color_scheme_1_3,
                R.color.color_scheme_1_4);
        return true;

    case R.id.menu_color_scheme_2:
        Log.i(LOG_TAG, "setColorScheme #2");
        item.setChecked(true);

        // Change the colors displayed by the SwipeRefreshLayout by providing it with 4
        // color resource ids
        setColorScheme(R.color.color_scheme_2_1, R.color.color_scheme_2_2, R.color.color_scheme_2_3,
                R.color.color_scheme_2_4);
        return true;

    case R.id.menu_color_scheme_3:
        Log.i(LOG_TAG, "setColorScheme #3");
        item.setChecked(true);

        // Change the colors displayed by the SwipeRefreshLayout by providing it with 4
        // color resource ids
        setColorScheme(R.color.color_scheme_3_1, R.color.color_scheme_3_2, R.color.color_scheme_3_3,
                R.color.color_scheme_3_4);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.thatkawaiiguy.meleehandbook.MainActivity.java

private void selectDrawerItem(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
    case R.id.advancedtech:
        mTitle = getString(R.string.title_advancedtech);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);/*from   w  w w .  jav a  2s. c om*/
        menuItem.setChecked(true);
        sendToast();
        break;
    case R.id.characters:
        mTitle = getString(R.string.title_characters);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);
        menuItem.setChecked(true);
        break;
    case R.id.fundamentals:
        mTitle = getString(R.string.title_fundamentals);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);
        menuItem.setChecked(true);
        break;
    case R.id.mu:
        mTitle = getString(R.string.title_matchups);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);
        menuItem.setChecked(true);
        break;
    case R.id.stages:
        mTitle = getString(R.string.title_stages);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);
        menuItem.setChecked(true);
        break;
    case R.id.term:
        mTitle = getString(R.string.title_term);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);
        menuItem.setChecked(true);
        break;
    case R.id.uniquetech:
        mTitle = getString(R.string.title_uniquetech);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(mTitle);
        menuItem.setChecked(true);
        sendToast();
        break;
    case R.id.healthy:
        mTitle = getString(R.string.title_healthy);
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(mTitle);
        changeFragment(getString(R.string.title_healthy));
        menuItem.setChecked(true);
        break;
    case R.id.remove:
        if (bp.isPurchased(getResources().getString(R.string.adproductid)))
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://bit" + ".ly/1NXCD2o")));

        else if (BillingProcessor.isIabServiceAvailable(this)) {
            bp.purchase(this, getResources().getString(R.string.adproductid));
        } else {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://bit" + ".ly/1NXCD2o")));
        }
        /*Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
                sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
        PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
        startIntentSenderForResult(pendingIntent.getIntentSender(),
                1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
                Integer.valueOf(0));
        */

        /*Intent serviceIntent =
                new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        */
        break;
    case R.id.settings:
        startActivity(new Intent(this, AppSettingsActivity.class));
        break;
    case R.id.about:
        new AboutDialogFragment().show(getFragmentManager(), "about");
        break;
    }
    mDrawer.closeDrawers();
}

From source file:at.tm.android.fitacity.MainActivity.java

/**
 * Method to display the category data//www.j  a  v  a2 s.c  o  m
 *
 * @param categories - category list to display
 */
private void setCategoriesMenu(List<Category> categories) {
    // If the provided category data is valid
    if (categories != null) {
        mCategoryMenuMap = new HashMap<>();

        // Add the category data to the main menu
        for (Category category : categories) {
            int itemId = View.generateViewId();

            mCategoryMenuMap.put(itemId, category);
            MenuItem menuItem = mNavigationView.getMenu().getItem(0).getSubMenu().add(0, itemId, 0,
                    category.getName());

            menuItem.setCheckable(true);
            menuItem.setIcon(R.drawable.ic_dashboard);

            // If the selected category id is the actual category id, set the menu item to checked
            if (category.getId() == mSelectedCategoryId) {
                menuItem.setChecked(true);
            }
        }
    }

    if (mSelectedCategoryId == FAVORITE_CATEGORY_ID) {
        MenuItem menuItem = mNavigationView.getMenu().getItem(1);
        menuItem.setChecked(true);
    }
}

From source file:de.chaosdorf.meteroid.BookingActivity.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.edit_hostname:
        Utility.startActivity(activity, SetHostname.class);
        break;/*from   w  w w . ja va  2  s .  c o m*/
    case R.id.reset_username:
        Utility.resetUsername(activity);
        Utility.startActivity(activity, PickUsername.class);
        break;
    case R.id.use_grid_view:
        useGridView = Utility.toggleUseGridView(activity);
        item.setChecked(useGridView);
        Utility.startActivity(activity, BookingActivity.class);
        break;
    case R.id.multi_user_mode:
        multiUserMode = MenuUtility.onClickMultiUserMode(this, item);
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:ca.six.unittestapp.todo.statistics.StatisticsActivity.java

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override/*from   www.j  a v  a  2 s.  com*/
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
            case R.id.list_navigation_menu_item:
                Intent intent = new Intent(StatisticsActivity.this, TasksActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                break;
            case R.id.statistics_navigation_menu_item:
                // Do nothing, we're already on that screen
                break;
            default:
                break;
            }
            // Close the navigation drawer when an item is selected.
            menuItem.setChecked(true);
            mDrawerLayout.closeDrawers();
            return true;
        }
    });
}

From source file:org.chatsecure.pushdemo.MainActivity.java

/** Navigation drawer item selection */
@Override//w  w  w.  ja  v a2  s  .  c  om
public boolean onNavigationItemSelected(MenuItem menuItem) {

    switch (menuItem.getItemId()) {
    case R.id.my_tokens:
        setContentFragment(TokensFragment.newInstance(client, dataProvider), R.string.my_tokens);
        break;

    case R.id.my_devices:
        setContentFragment(DevicesFragment.newInstance(client, dataProvider), R.string.my_devices);
        break;

    case R.id.messaging:
        setContentFragment(MessagingFragment.newInstance(client, dataProvider), R.string.messaging);
        break;
    }

    menuItem.setChecked(true);
    drawer.closeDrawers();
    return true;
}

From source file:com.mycompany.myfirstindoorsapp.PagedActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.pointMode:
        item.setChecked(true);
        mesureMode = POINTMODE;/*from  ww w.  j a  v  a 2  s. c  o  m*/
        createdOverlays = refreshOverlay(createdOverlays);
        twoPoints[0] = null;
        twoPoints[1] = null;
        singlePoint = null;
        return true;
    case R.id.lineMode:
        item.setChecked(true);
        mesureMode = LINEMODE;
        createdOverlays = refreshOverlay(createdOverlays);
        twoPoints[0] = null;
        twoPoints[1] = null;
        singlePoint = null;
        return true;
    case R.id.menu_startMesurement:
        // begin mesurement
        if ((currentPosition == null) || ((singlePoint == null) && (twoPoints[0] == null))) {
            Toast.makeText(this, "Set pts", Toast.LENGTH_SHORT).show();
        } else {

            double[] coord = new double[4];
            coord[0] = currentPosition.x;
            coord[1] = currentPosition.y;
            coord[2] = 0;
            coord[3] = 0;
            RealVector x = new ArrayRealVector(coord);
            kalman = new Kalman(accelNoise, measurementNoise, x);
            accel.start(mesureMode);
            if ((mesureMode == POINTMODE) && (singlePoint != null)) {
                data = new Data(singlePoint);
                Toast.makeText(this, "new Data (singlePoint)", Toast.LENGTH_SHORT).show();
            }
            if ((mesureMode == LINEMODE) && (twoPoints[0] != null) && (twoPoints[1] != null)) {
                data = new Data(twoPoints[0], twoPoints[1], SystemClock.uptimeMillis());
                Toast.makeText(this, "new Data (twoPoints)", Toast.LENGTH_SHORT).show();
            }
            if ((twoPoints[0] != null) && (twoPoints[1] != null) && (singlePoint != null)) {
                Toast.makeText(this, "singlePoint!=!=!null!=!=!twoPoints[0][1]", Toast.LENGTH_SHORT).show();
            }
            if ((twoPoints[0] == null) && (twoPoints[1] == null) && (singlePoint == null)) {
                Toast.makeText(this, "singlePoint==null==twoPoints[0][1]", Toast.LENGTH_SHORT).show();
            }
        }
        return true;
    case R.id.menu_stopMesurement:
        if (null != data) {
            double[] standartDeviations = data.calc(SystemClock.uptimeMillis());
            accel.stop();
            kalman = null;
            fragment.addItem(pagedActivity, indoorsSurfaceFragment, "Deviation for indoors="
                    + standartDeviations[0] + "; and for Kalman=" + standartDeviations[1],
                    new Coordinate(0, 0, 0));

            Toast.makeText(this, "Deviation for indoors=" + standartDeviations[0] + "; and for " + "Kalman="
                    + standartDeviations[1], Toast.LENGTH_LONG).show();
            data = null;
            if (overlayKalman != null) {
                indoorsSurfaceFragment.removeOverlay(overlayKalman);
                indoorsSurfaceFragment.updateSurface();
            }
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.cyanogenmod.effem.FmRadio.java

/**
 * React to a selection in the option menu
 *//* ww w  .jav  a  2s .c  om*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getGroupId()) {
    case BAND_SELECTION_MENU:
        switch (item.getItemId()) {
        case BAND_US:
            mSelectedBand = FmBand.BAND_US;
            item.setChecked(true);
            break;
        case BAND_EU:
            mSelectedBand = FmBand.BAND_EU;
            item.setChecked(true);
            break;
        case BAND_JAPAN:
            mSelectedBand = FmBand.BAND_JAPAN;
            item.setChecked(true);
            break;
        case BAND_CHINA:
            mSelectedBand = FmBand.BAND_CHINA;
            item.setChecked(true);
            break;
        default:
            break;
        }
        mWorkerHandler.post(new Runnable() {
            public void run() {
                mService.stopRadio();
                mService.startRadio(mSelectedBand, 0, mSelectedOutput);
            }
        });
        break;

    case LOUDSPEAKER_SELECTION_MENU:
        mSelectedOutput = (item.getItemId() == OUTPUT_HEADSET) ? 0 : 1;
        mWorkerHandler.post(new Runnable() {
            public void run() {
                mService.stopRadio();
                mService.startRadio(mSelectedBand, mCurrentFrequency, mSelectedOutput);
            }
        });
        break;

    case STATION_SELECTION_MENU:
        final int freq = mMenuAdapter.getItem(getSelectStationMenuItem(item)).frequency;
        mWorkerHandler.post(new Runnable() {
            public void run() {
                if (!mService.isStarted())
                    mService.startRadio(mSelectedBand, freq, mSelectedOutput);
                else
                    mService.changeFrequency(FmRadioService.SEEK_ABSOLUTE, freq);
            }
        });
        break;
    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.example.sans.myapplication.Utility.Map.MapsActivity.java

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

    shares = getSharedPreferences("SHARES", 0);

    controller = (AppController) getApplication();

    receiver = new MyReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.intent.action.test");
    this.registerReceiver(receiver, filter);

    Intent i = getIntent();//from www  . j a  v a  2s  . c  o  m

    Bundle bundle = i.getExtras();

    try {
        j = new JSONObject(bundle.getString("data", "ERROR"));
        shares.edit().putString("ORDER", bundle.getString("data", "ERROR")).commit();
    } catch (JSONException e) {
        try {
            j = new JSONObject(shares.getString("ORDER", "ERROR"));
        } catch (JSONException e1) {
            SharedPreferences.Editor editor = shares.edit();
            final Client client = new Client();
            RequestParams params = new RequestParams();
            params.put("id", shares.getInt("ID", 0));
            params.put("status", 999);
            client.post("driver/setStatus", params, new JsonHttpResponseHandler());

            editor.putBoolean("ONLINE", false);
            editor.putBoolean("LOGIN", false);
            editor.commit();
            Intent intent = getApplicationContext().getPackageManager()
                    .getLaunchIntentForPackage(getApplicationContext().getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }

    try {
        Log.e("PHONE_NO", String.valueOf(j.getJSONObject("passenger_data")));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    pass_phone = (ImageView) findViewById(R.id.pass_phone);
    pass_phone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent phoneIntent = null;
            try {
                phoneIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("tel:" + j.getJSONObject("passenger_data").getString("tel")));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            startActivity(phoneIntent);
        }
    });
    pass_msg = (ImageView) findViewById(R.id.pass_msg);
    pass_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent msgIntent = new Intent(Intent.ACTION_VIEW);

            try {
                msgIntent.setData(Uri.parse("sms:" + j.getJSONObject("passenger_data").getString("tel")));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            startActivity(msgIntent);
        }
    });

    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);

    TextView actionBarTitle = (TextView) toolbar.findViewById(R.id.action_bar_title);

    try {
        actionBarTitle.setText(j.getJSONObject("passenger_data").getString("family_name")
                + j.getJSONObject("passenger_data").getString("title"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    setUpMapIfNeeded();

    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    header = navigationView.inflateHeaderView(R.layout.header);
    JSONObject driver_data = null;
    try {
        driver_data = new JSONObject(shares.getString("DRIVER_DATA", "ERROR"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    TextView driver_name_header = (TextView) header.findViewById(R.id.username);
    TextView car_id_header = (TextView) header.findViewById(R.id.car_id);
    final ImageView pp_header = (ImageView) header.findViewById(R.id.profile_image);

    try {
        car_id_header.setText(driver_data.getString("license"));
        driver_name_header.setText(driver_data.getString("name"));
        Client client = new Client();
        client.get(driver_data.getString("image"),
                new FileAsyncHttpResponseHandler(MapsActivity.this.getApplicationContext()) {
                    @Override
                    public void onFailure(int i, Header[] headers, Throwable throwable, File file) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final File response) {

                        MapsActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap image = BitmapFactory.decodeFile(response.getPath());

                                pp_header.setImageBitmap(image);

                            }
                        });

                    }

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

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

            Intent i = new Intent(MapsActivity.this, MenuItemActivity.class);
            i.putExtra("MENU_ITEM", 0);
            MapsActivity.this.startActivity(i);
            drawerLayout.closeDrawers();
        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state

            nav = true;

            menuItem.setChecked(false);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Fragment fragment;
            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {
            case R.id.timetable:
            case R.id.service:
            case R.id.history:
            case R.id.mission:
            case R.id.points:
            case R.id.notice:
                Intent i = new Intent(MapsActivity.this, MenuItemActivity.class);
                i.putExtra("MENU_ITEM", menuItem.getItemId());
                MapsActivity.this.startActivity(i);
                break;
            case R.id.login:
                //Toast.makeText(getApplicationContext(), "Logout Selected", Toast.LENGTH_SHORT).show();
                SharedPreferences.Editor editor = shares.edit();

                final Client client = new Client();
                RequestParams params = new RequestParams();
                params.put("id", shares.getInt("ID", 0));
                params.put("status", 999);
                client.post("driver/setStatus", params, new JsonHttpResponseHandler());

                editor.putBoolean("ONLINE", false);
                editor.putBoolean("LOGIN", false);
                editor.commit();
                Intent intent = getApplicationContext().getPackageManager()
                        .getLaunchIntentForPackage(getApplicationContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                //Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
                break;

            }
            return false;
        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
            drawerLayout.setSelected(false);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //calling sync state is necessay or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();
}