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:org.comixwall.pffw.MainActivity.java

/**
 * Select the fragment to display.//from w w w  .  ja v  a 2  s  .c  o m
 * We modify the backstack ourselves so that no fragment is pushed to the backstack twice.
 * So if a fragment which is already in the backstack is selected, we roll back the backstack
 * to its position.
 * <p>
 * We never push the Dashboard fragment to the backstack because it is always
 * the first fragment displayed (if we push it to the backstack too, pressing the back button
 * while Dashboard fragment is displayed causes a blank activity screen).
 *
 * @param item The menu item selected.
 * @return See {@link NavigationView.OnNavigationItemSelectedListener}
 */
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    // Ignore requests for the same fragment already displayed
    if (!mMenuItems2Fragments.get(id).isInstance(fragment)) {
        FragmentManager fm = getSupportFragmentManager();

        boolean add = true;

        if (id == R.id.menuDashboard) {
            // Dashboard is the main fragment, should never be removed,
            // so remove all backstack entries first to reach the first Dashboard.
            popAllBackStack();

            // Never add Dashboard to the backstack
            add = false;
            fragment = new Dashboard();

            // ATTENTION: menuDashboard does not check initially, so we need to manage it ourselves
            item.setChecked(true);
        } else {
            // TODO: Check why android:checkableBehavior="single" does not uncheck menuDashboard
            MenuItem itemDashboard = navigationView.getMenu().findItem(R.id.menuDashboard);
            if (itemDashboard.isChecked()) {
                itemDashboard.setChecked(false);
            }

            try {
                fragment = (Fragment) mMenuItems2Fragments.get(id).getConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
                logger.severe("EXCEPTION: " + e.toString());
                return false;
            }
        }

        String fragmentName = fragment.getClass().getSimpleName();

        // Rolls back the backstack if the fragment is already in
        if (!fm.popBackStackImmediate(fragmentName, 0)) {
            android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

            if (add) {
                transaction.addToBackStack(fragmentName);
            }

            // TODO: Check if we need to pass any args
            //fragment.setArguments(getIntent().getExtras());
            transaction.replace(R.id.fragmentContainer, fragment);

            transaction.commit();
        }
    } else {
        logger.finest("onNavigationItemSelected will not show the same fragment");
    }

    drawer.closeDrawer(GravityCompat.START);
    createOptionsMenu();
    return true;
}

From source file:com.sourceauditor.sahomemonitor.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_display_reg) {
        showRegistrationId();//  w ww  .  java 2s. c om
        return true;
    } else if (id == R.id.action_show_last_home_message) {
        showLastHomeMessage();
        return true;
    } else if (id == R.id.action_speaker) {
        if (audioManager.isSpeakerphoneOn()) {
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.setSpeakerphoneOn(false);
            item.setChecked(false);
        } else {
            audioManager.setMode(AudioManager.MODE_NORMAL);
            audioManager.setSpeakerphoneOn(true);
            item.setChecked(true);
        }

    } else if (id == R.id.action_show_home_monitor_url) {
        showUrl();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.joeyturczak.jtscanner.ui.MainActivity.java

public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the planet to show based on
    // position//from w  w  w.  jav a2 s  .  c o m
    if (!menuItem.isChecked()) {

        switch (menuItem.getItemId()) {
        case R.id.scanner_fragment:
            startScannerFragment();
            break;
        case R.id.scan_list_fragment:
            startScanListFragment();
            break;
        case R.id.settings_fragment:
            startSettingsFragment();
            break;
        case R.id.file_list_fragment:
            startFileListFragment();
            break;
        case R.id.about:
            startAboutFragment();
            break;
        default:
            startScannerFragment();
        }

        // Highlight the selected item, update the title, and close the drawer
        setTitle(menuItem.getTitle());
        menuItem.setChecked(true);
    }
    mDrawerLayout.closeDrawers();
}

From source file:com.murrayc.galaxyzoo.app.QuestionFragment.java

@Override
public void onPrepareOptionsMenu(final Menu menu) {
    super.onPrepareOptionsMenu(menu);

    //Before the menu item is displayed,
    //make sure that the checked state is correct:
    final MenuItem item = menu.findItem(R.id.option_menu_item_favorite);
    if (item != null) {
        boolean checked = false;
        if (mClassificationInProgress != null) {
            checked = mClassificationInProgress.isFavorite();
        }/*from   w w w.  j  ava 2s  .c o m*/
        item.setChecked(checked);
    }
}

From source file:de.aw.monma.mainscreen.FragmentPassport.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;/* w  w  w .ja v a2 s.  co m*/
    boolean consumed = false;
    switch (item.getItemId()) {
    case R.id.menu_item_showUmsaetze:
        intent = new Intent(getActivity(), ActivityHBCIActions.class);
        intent.putExtra(ACTION, (Parcelable) MonMaInterface.Action.ShowNeueOnlineUmsaetze);
        startActivity(intent);
        return true;
    case R.id.menu_item_exportDepots:
        // Export der Wertpapiere der Online-Depots
        DBDefinition tbd = DBDefinition.UmsatzView;
        String[] projection = new String[] { column_wpid, column_partnername, _id,
                AbstractDBHelper.SQLSumItem(column_bestand) };
        String selection = " GROUP BY " + column_wpid;
        Cursor c = getActivity().getContentResolver().query(tbd.getUri(), projection, selection, null, null);
        if (mCSVExporter == null) {
            mCSVExporter = new CSVExporter(getContext(), this);
        }
        mCSVExporter.doExport(tbd, c);
        consumed = true;
        break;
    case R.id.menu_item_hideDetails:
        zeigeDetails = !zeigeDetails;
        item.setChecked(zeigeDetails);
        getAdapter().notifyDataSetChanged();
        prefs.edit().putBoolean(getString(R.string.cbDetailAnzeigeBank), zeigeDetails).apply();
        consumed = true;
        break;
    case R.id.menu_item_HBCIKontoRundruf:
        if (AWUtils.hasInternetConnection(getActivity())) {
            String key = prefs.getString(getString(R.string.key), null);
            if (key != null) {
                intent = new Intent(getActivity(), HBCIService.class);
                intent.putExtra(HBCIACTION, ExecuteHBCICall);
                intent.putExtra(USERACTION, true);
                getActivity().startService(intent);
            } else {
                DialogFragment dlg = new FragmentMasterPassword();
                dlg.show(getFragmentManager(), null);
            }
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.NoInternetConnection);
            builder.setMessage(R.string.NoInternetConnection);
            builder.setPositiveButton(R.string.awlib_btnAccept, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            Dialog dlg = builder.create();
            dlg.show();
        }
        consumed = true;
        break;
    }
    if (!consumed) {
        consumed = super.onOptionsItemSelected(item);
    }
    return consumed;
}

From source file:com.techno.jay.codingcontests.Home.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    FirebaseApp.initializeApp(this);

    FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "fonts/ProductSans-Regular.ttf");
    fontChanger.replaceFonts((ViewGroup) this.findViewById(android.R.id.content));
    //==2) for fragment hoy to====
    //== fontChanger.replaceFonts((ViewGroup) this.getView());
    //===3) for adepterview and handlerview na use mate====
    //==convertView = inflater.inflate(R.layout.listitem, null);
    //==fontChanger.replaceFonts((ViewGroup)convertView);

    bp = new BillingProcessor(Home.this, Const.LICENSE_KEY, Home.this);
    /*bp.consumeAsync(inventory.getPurchase(SKU_GAS),
        mConsumeFinishedListener);*/
    bp.consumePurchase(Const.Product_Plan_Unlimitedversion);

    Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from   ww  w. j a  v  a  2  s.com

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.appicon);

    /*     if (Build.VERSION.SDK_INT >= 21) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.setStatusBarColor(Color.parseColor("#1976D2"));
    window.setNavigationBarColor(Color.parseColor("#1976D2"));
         }*/

    sharepref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(
                android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[] { android.Manifest.permission.READ_PHONE_STATE },
                    PERMISSIONS_REQUEST_READ_PHONE_STATE);
        } else {
            getDeviceImei();
        }
    } else {
        getDeviceImei();
    }

    databaseReferenceUser = FirebaseDatabase.getInstance().getReference("Users");
    //databaseReferenceUser.keepSynced(true);

    token = FirebaseInstanceId.getInstance().getToken();

    SimpleDateFormat format_diffrent = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    Date now = new Date();
    date = format_diffrent.format(now);

    // creating connection detector class instance
    ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
    // get Internet status
    isInternetPresent = cd.isConnectingToInternet();
    if (isInternetPresent) {
        // Internet Connection is Present
        // make HTTP requests
        //refreshedToken = FirebaseInstanceId.getInstance().getToken();
        databaseReferenceUser.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get user value

                if (dataSnapshot.hasChild(str_IMEI)) {
                    String IMEI_no = dataSnapshot.child("IMEI").getValue(String.class);
                    String date_got = dataSnapshot.child("date").getValue(String.class);
                    Log.d("date got", date_got);
                    String status_got = dataSnapshot.child("status").getValue(String.class);

                    Toast.makeText(Home.this, "  Already registered. !   ", Toast.LENGTH_LONG).show();
                    SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

                    try {
                        Date date1 = myFormat.parse(date_got);
                        Date date2 = myFormat.parse(date);
                        long diff = date2.getTime() - date1.getTime();
                        System.out.println("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

                        long days_count = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

                        if (days_count > 10 && status_got.equalsIgnoreCase("inactive")) {
                            promptForUpgrade();
                        }

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

            @Override
            public void onCancelled(DatabaseError databaseError) {
                //  Log.w("TAG", "getUser:onCancelled", databaseError.toException());
                // new Signup_async().execute();
            }
        });

    } else {

        Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), " Sorry! No Internet!!!",
                Snackbar.LENGTH_LONG);

        // Changing message text color
        snackbar.setActionTextColor(Color.BLUE);

        // Changing action button text color
        View sbView = snackbar.getView();
        TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(Color.YELLOW);
        snackbar.show();

        Toast.makeText(Home.this, "  No Internet Connection!!!.  ", Toast.LENGTH_LONG).show();

    }

    Set<String> set = sharepref.getStringSet("arraylist", null);
    List<String> sposers = new ArrayList<String>(set);

    String[] apossor_arry = new String[sposers.size()];
    apossor_arry = sposers.toArray(apossor_arry);

    FragmentTransaction tx;
    tx = getSupportFragmentManager().beginTransaction();
    tx.replace(R.id.frame, new MainHomeFragmentFirebase());
    tx.commit();

    searchView = (MaterialSearchView) findViewById(R.id.search_view);
    searchView.setVoiceSearch(false);
    searchView.setHint("Enter Coding website/technology");
    searchView.setCursorDrawable(R.drawable.custome_cursor);
    searchView.setSuggestions(apossor_arry);
    searchView.setEllipsize(true);

    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Snackbar.make(findViewById(android.R.id.content), "Query: " + query, Snackbar.LENGTH_LONG).show();
            Intent result = new Intent(Home.this, ResultContestLink.class);
            result.putExtra("query", query);

            startActivity(result);
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            //Do some magic
            return false;
        }
    });

    searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {
            //Do some magic
        }

        @Override
        public void onSearchViewClosed() {
            //Do some magic
        }
    });

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle Toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close) {

        @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);
        }

        @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
    drawer.setDrawerListener(Toggle);
    //calling sync state is necessay or else your hamburger icon wont show up
    Toggle.syncState();

    databaseReferenceEventData = FirebaseDatabase.getInstance().getReference("Contest").child("objects");
    databaseReferenceEventData.keepSynced(true);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.nav_view);

    Menu m = navigationView.getMenu();
    for (int i = 0; i < m.size(); i++) {
        MenuItem mi = m.getItem(i);

        //for aapplying a font to subMenu ...
        SubMenu subMenu = mi.getSubMenu();
        if (subMenu != null && subMenu.size() > 0) {
            for (int j = 0; j < subMenu.size(); j++) {
                MenuItem subMenuItem = subMenu.getItem(j);
                applyFontToMenuItem(subMenuItem);
            }
        }

        //the method we have create in activity
        applyFontToMenuItem(mi);
    }

    View header = navigationView.getHeaderView(0);
    tv_total_sponsers = (TextView) header.findViewById(R.id.tv_total_sponsers);
    tv_total_contests = (TextView) header.findViewById(R.id.tv_total_contests);

    tv_total_sponsers.setText("Total Contests websites : " + sharepref.getString("totalsposor", "NA"));

    // navigationView.setNavigationItemSelectedListener(this);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    assert navigationView != null;
    navigationView.setCheckedItem(R.id.nav_home);
    navigationView.getMenu().getItem(0).setChecked(true);
    navigationView.setItemIconTintList(null);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

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

            navigationView.getMenu().getItem(0).setChecked(false);

            //Checking if the item is in checked state or not, if not make it in checked state
            if (activeMenuItem != null)
                activeMenuItem.setChecked(false);
            activeMenuItem = menuItem;
            menuItem.setChecked(true);
            //else menuItem.setChecked(true);

            //Closing drawer on item click
            drawer.closeDrawers();
            Fragment fragment = null;
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {

            //Replacing the main content with ContentFragment Which is our Inbox View;
            case R.id.nav_home:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new MainHomeFragmentFirebase();
                break;

            case R.id.nav_longcompetition:

                fragment = new LongtermCompetition();
                break;
            case R.id.nav_exit:
                System.exit(0);
                getIntent().setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                break;
            case R.id.nav_running:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new LiveContests();
                break;

            case R.id.nav_past:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new CompletedContest();
                break;

            case R.id.nav_share:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();

                Intent intentshare = new Intent(Intent.ACTION_SEND);
                intentshare.setType("text/plain");
                intentshare.putExtra(Intent.EXTRA_TEXT,
                        "Best Competitive Programming news/reminder app for Coders.World wide coding competitions and hiring challenges.Solve the challenges and get chance to win awesome prizes and also hired by world famous MNCs(i.e AMAZON , IBM , intel , google , SAP many more...).\n\n\n"
                                + "https://play.google.com/store/apps/details?id=com.techno.jay.codingcontests&hl=en"
                                + "\n\n-developed by Technocrats Appware");
                startActivity(Intent.createChooser(intentshare, "Share"));

                break;
            case R.id.nav_feedback:
                final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
                try {
                    startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                } catch (Exception e) {
                    // Log.d("TAG","Message ="+e);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "https://play.google.com/store/apps/details?id=com.techno.jay.codingcontests&hl=en")));
                }
                break;

            case R.id.nav_hiring:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                Intent result = new Intent(Home.this, ResultContestLink.class);
                result.putExtra("query", "hiring");

                startActivity(result);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;

            case R.id.nav_setting:
                Intent seting = new Intent(Home.this, Setting_app.class);
                startActivity(seting);
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                break;

            case R.id.nav_aboutus:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment = new Aboutus();
                break;

            /*case R.id.nav_aboutus:
                // Toast.makeText(getApplicationContext(),"Shop",Toast.LENGTH_SHORT).show();
                fragment= new Aboutus_fragment();
                break;
                    
            case R.id.spam:
                Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
                return true;*/
            default:
                Toast.makeText(getApplicationContext(), "Coming Soon...", Toast.LENGTH_SHORT).show();

                break;

            }

            if (fragment != null) {

                fragmentTransaction.replace(R.id.frame, fragment);
                //getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
                fragmentTransaction.addToBackStack(null).commit();

                getSupportActionBar().setTitle("Coding Contests");

            } else {
                menuItem.setChecked(false);
            }

            return true;
        }
    });

}

From source file:gc.david.dfm.ui.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    DFMLogger.logMessage(TAG, "onCreate savedInstanceState=" + Utils.dumpBundleToString(savedInstanceState));

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DaggerMainComponent.builder().rootModule(new RootModule((DFMApplication) getApplication()))
            .storageModule(new StorageModule()).mainModule(new MainModule()).build().inject(this);
    bind(this);//from  w w w .  ja  va 2 s.co  m

    setSupportActionBar(tbMain);

    final ActionBar supportActionBar = getSupportActionBar();
    if (supportActionBar != null) {
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeButtonEnabled(true);
        final Drawable upArrow = ContextCompat.getDrawable(appContext, R.drawable.ic_menu_white_24dp);
        supportActionBar.setHomeAsUpIndicator(upArrow);
    }

    elevationPresenter = new ElevationPresenter(this, elevationUseCase, connectionManager, preferencesProvider);
    addressPresenter = new AddressPresenter(this, getAddressCoordinatesByNameUseCase,
            getAddressNameByCoordinatesUseCase, connectionManager);

    final SupportMapFragment supportMapFragment = ((SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map));
    supportMapFragment.getMapAsync(this);

    if (!connectionManager.isOnline()) {
        showConnectionProblemsDialog();
    }

    handleIntents(getIntent());

    nvDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            drawerLayout.closeDrawers();
            switch (menuItem.getItemId()) {
            case R.id.menu_current_position:
                menuItem.setChecked(true);
                onStartingPointSelected();
                if (SDK_INT >= M && !isLocationPermissionGranted()) {
                    Snackbar.make(drawerLayout, "This feature needs location permissions.",
                            Snackbar.LENGTH_INDEFINITE).setAction("Settings", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    final Intent intent = new Intent(
                                            android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    startActivity(intent);
                                }
                            }).show();
                }
                return true;
            case R.id.menu_any_position:
                menuItem.setChecked(true);
                onStartingPointSelected();
                return true;
            case R.id.menu_rate_app:
                showRateDialog();
                return true;
            case R.id.menu_settings:
                SettingsActivity.open(MainActivity.this);
                return true;
            case R.id.menu_help_feedback:
                HelpAndFeedbackActivity.open(MainActivity.this);
                return true;
            case R.id.menu_about:
                AboutActivity.open(MainActivity.this);
                return true;
            }
            return false;
        }
    });
}

From source file:github.popeen.dsub.activity.SubsonicFragmentActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState == null) {
        String fragmentType = getIntent().getStringExtra(Constants.INTENT_EXTRA_FRAGMENT_TYPE);
        boolean firstRun = false;
        if (fragmentType == null) {
            fragmentType = Util.openToTab(this);
            if (fragmentType != null) {
                firstRun = true;//from  w  w w  .  j  a v  a 2s.co  m
            }
        }

        if ("".equals(fragmentType) || fragmentType == null || firstRun) {
            // Initial startup stuff
            if (!sessionInitialized) {
                loadSession();
            }
        }
    }

    super.onCreate(savedInstanceState);
    if (getIntent().hasExtra(Constants.INTENT_EXTRA_NAME_EXIT)) {
        stopService(new Intent(this, DownloadService.class));
        finish();
        getImageLoader().clearCache();
        DrawableTint.clearCache();
    } else if (getIntent().hasExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD_VIEW)) {
        getIntent().putExtra(Constants.INTENT_EXTRA_FRAGMENT_TYPE, "Download");
        lastSelectedPosition = R.id.drawer_downloading;
    }
    setContentView(R.layout.abstract_fragment_activity);

    if (findViewById(R.id.fragment_container) != null && savedInstanceState == null) {
        String fragmentType = getIntent().getStringExtra(Constants.INTENT_EXTRA_FRAGMENT_TYPE);
        if (fragmentType == null) {
            fragmentType = Util.openToTab(this);
            if (fragmentType != null) {
                getIntent().putExtra(Constants.INTENT_EXTRA_FRAGMENT_TYPE, fragmentType);
                lastSelectedPosition = getDrawerItemId(fragmentType);
            } else {
                lastSelectedPosition = R.id.drawer_home;
            }

            MenuItem item = drawerList.getMenu().findItem(lastSelectedPosition);
            if (item != null) {
                item.setChecked(true);
            }
        } else {
            lastSelectedPosition = getDrawerItemId(fragmentType);
        }

        currentFragment = getNewFragment(fragmentType);
        if (getIntent().hasExtra(Constants.INTENT_EXTRA_NAME_ID)) {
            Bundle currentArguments = currentFragment.getArguments();
            if (currentArguments == null) {
                currentArguments = new Bundle();
            }
            currentArguments.putString(Constants.INTENT_EXTRA_NAME_ID,
                    getIntent().getStringExtra(Constants.INTENT_EXTRA_NAME_ID));
            currentFragment.setArguments(currentArguments);
        }
        currentFragment.setPrimaryFragment(true);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, currentFragment, currentFragment.getSupportTag() + "").commit();

        if (getIntent().getStringExtra(Constants.INTENT_EXTRA_NAME_QUERY) != null) {
            SearchFragment fragment = new SearchFragment();
            replaceFragment(fragment, fragment.getSupportTag());
        }

        // If a album type is set, switch to that album type view
        String albumType = getIntent().getStringExtra(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_TYPE);
        if (albumType != null) {
            SubsonicFragment fragment = new SelectDirectoryFragment();

            Bundle args = new Bundle();
            args.putString(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_TYPE, albumType);
            args.putInt(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_SIZE, 20);
            args.putInt(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_OFFSET, 0);

            fragment.setArguments(args);
            replaceFragment(fragment, fragment.getSupportTag());
        }
    }

    slideUpPanel = (SlidingUpPanelLayout) findViewById(R.id.slide_up_panel);
    panelSlideListener = new SlidingUpPanelLayout.PanelSlideListener() {
        @Override
        public void onPanelSlide(View panel, float slideOffset) {

        }

        @Override
        public void onPanelCollapsed(View panel) {
            isPanelClosing = false;
            if (bottomBar.getVisibility() == View.GONE) {
                bottomBar.setVisibility(View.VISIBLE);
                nowPlayingToolbar.setVisibility(View.GONE);
                nowPlayingFragment.setPrimaryFragment(false);
                setSupportActionBar(mainToolbar);
                recreateSpinner();
            }
        }

        @Override
        public void onPanelExpanded(View panel) {
            isPanelClosing = false;
            currentFragment.stopActionMode();

            // Disable custom view before switching
            getSupportActionBar().setDisplayShowCustomEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(true);

            bottomBar.setVisibility(View.GONE);
            nowPlayingToolbar.setVisibility(View.VISIBLE);
            setSupportActionBar(nowPlayingToolbar);

            if (secondaryFragment == null) {
                nowPlayingFragment.setPrimaryFragment(true);
            } else {
                secondaryFragment.setPrimaryFragment(true);
            }

            drawerToggle.setDrawerIndicatorEnabled(false);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        @Override
        public void onPanelAnchored(View panel) {

        }

        @Override
        public void onPanelHidden(View panel) {
        }
    };
    slideUpPanel.setPanelSlideListener(panelSlideListener);

    if (getIntent().hasExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD)) {
        // Post this later so it actually runs
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                openNowPlaying();
            }
        }, 200);

        getIntent().removeExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD);
    }

    bottomBar = findViewById(R.id.bottom_bar);
    mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
    nowPlayingToolbar = (Toolbar) findViewById(R.id.now_playing_toolbar);
    coverArtView = (ImageView) bottomBar.findViewById(R.id.album_art);
    trackView = (TextView) bottomBar.findViewById(R.id.track_name);
    artistView = (TextView) bottomBar.findViewById(R.id.artist_name);

    setSupportActionBar(mainToolbar);

    if (findViewById(R.id.fragment_container) != null && savedInstanceState == null) {
        nowPlayingFragment = new NowPlayingFragment();
        FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
        trans.add(R.id.now_playing_fragment_container, nowPlayingFragment, nowPlayingFragment.getTag() + "");
        trans.commit();
    }

    rewindButton = (ImageButton) findViewById(R.id.download_rewind);
    rewindButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) {
                @Override
                protected Void doInBackground() throws Throwable {
                    if (getDownloadService() == null) {
                        return null;
                    }

                    getDownloadService().rewind();
                    return null;
                }
            }.execute();
        }
    });

    previousButton = (ImageButton) findViewById(R.id.download_previous);
    previousButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) {
                @Override
                protected Void doInBackground() throws Throwable {
                    if (getDownloadService() == null) {
                        return null;
                    }

                    getDownloadService().previous();
                    return null;
                }
            }.execute();
        }
    });

    startButton = (ImageButton) findViewById(R.id.download_start);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) {
                @Override
                protected Void doInBackground() throws Throwable {
                    PlayerState state = getDownloadService().getPlayerState();
                    if (state == PlayerState.STARTED) {
                        getDownloadService().pause();
                    } else if (state == PlayerState.IDLE) {
                        getDownloadService().play();
                    } else {
                        getDownloadService().start();
                    }

                    return null;
                }
            }.execute();
        }
    });

    nextButton = (ImageButton) findViewById(R.id.download_next);
    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) {
                @Override
                protected Void doInBackground() throws Throwable {
                    if (getDownloadService() == null) {
                        return null;
                    }

                    getDownloadService().next();
                    return null;
                }
            }.execute();
        }
    });

    fastforwardButton = (ImageButton) findViewById(R.id.download_fastforward);
    fastforwardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SilentBackgroundTask<Void>(SubsonicFragmentActivity.this) {
                @Override
                protected Void doInBackground() throws Throwable {
                    if (getDownloadService() == null) {
                        return null;
                    }

                    getDownloadService().fastForward();
                    return null;
                }
            }.execute();
        }
    });
}

From source file:com.usabusi.newsreader.HeadlinesFragment.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 ww .j  a  va 2s . co m
 */
@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_url:
        // Launch settings activity
        //http://stackoverflow.com/questions/15514831/starting-new-activity-from-listfragment-using-onlistitemclick
        // intent = new Intent(this, PreferencesActivitySummary.class);
        Intent i = new Intent(getActivity().getApplicationContext(), PreferencesActivitySummary.class);
        HeadlinesFragment.this.startActivity(i);
        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.zhengde163.netguard.ActivityMain.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.i(TAG, "Menu=" + item.getTitle());
    // Handle item selection
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    switch (item.getItemId()) {
    case R.id.menu_app_user:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("show_user", item.isChecked()).apply();
        return true;

    case R.id.menu_app_system:
        item.setChecked(!item.isChecked());
        prefs.edit().putBoolean("show_system", item.isChecked()).apply();
        return true;

    case R.id.menu_app_nointernet:
        boolean nointernet = prefs.getBoolean("show_nointernet", true);
        nointernet = !nointernet;/*from   w ww . j  av  a  2s .c o  m*/
        if (nointernet)
            item.setIcon(R.drawable.checked);
        else
            item.setIcon(R.drawable.check);
        prefs.edit().putBoolean("show_nointernet", nointernet).apply();
        return true;

    case R.id.menu_app_disabled:
        boolean disabled = prefs.getBoolean("show_disabled", true);
        disabled = !disabled;
        if (disabled)
            item.setIcon(R.drawable.checked);
        else
            item.setIcon(R.drawable.check);
        prefs.edit().putBoolean("show_disabled", disabled).apply();
        return true;

    case R.id.menu_sort_name:
        item.setChecked(true);
        item.setIcon(R.drawable.singlechecked);
        menu_data.setIcon(R.drawable.singlecheck);
        prefs.edit().putString("sort", "name").apply();
        return true;

    case R.id.menu_sort_data:
        item.setChecked(true);
        item.setIcon(R.drawable.singlechecked);
        menu_name.setIcon(R.drawable.singlecheck);
        prefs.edit().putString("sort", "data").apply();
        return true;

    case R.id.menu_log:
        startActivity(new Intent(this, ActivityLog.class));
        return true;

    case R.id.menu_settings:
        startActivity(new Intent(this, ActivitySettings.class));
        return true;

    case R.id.menu_legend:
        menu_legend();
        return true;

    case R.id.login_again:
        startActivity(new Intent(ActivityMain.this, LoginAgain.class));
        return true;

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