Example usage for android.widget PopupMenu getMenuInflater

List of usage examples for android.widget PopupMenu getMenuInflater

Introduction

In this page you can find the example usage for android.widget PopupMenu getMenuInflater.

Prototype

public MenuInflater getMenuInflater() 

Source Link

Usage

From source file:im.vector.adapters.VectorMessagesAdapter.java

/**
 * The user taps on the action icon.//w ww. j a  v a2  s .c om
 * @param event the selected event.
 * @param textMsg the event text
 * @param anchorView the popup anchor.
 */
@SuppressLint("NewApi")
private void onMessageClick(final Event event, final String textMsg, final View anchorView) {
    final PopupMenu popup = (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            ? new PopupMenu(mContext, anchorView, Gravity.END)
            : new PopupMenu(mContext, anchorView);

    popup.getMenuInflater().inflate(R.menu.vector_room_message_settings, popup.getMenu());

    // force to display the icons
    try {
        Field[] fields = popup.getClass().getDeclaredFields();
        for (Field field : fields) {
            if ("mPopup".equals(field.getName())) {
                field.setAccessible(true);
                Object menuPopupHelper = field.get(popup);
                Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
                Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
                setForceIcons.invoke(menuPopupHelper, true);
                break;
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "onMessageClick : force to display the icons failed " + e.getLocalizedMessage());
    }

    Menu menu = popup.getMenu();

    // hide entries
    for (int i = 0; i < menu.size(); i++) {
        menu.getItem(i).setVisible(false);
    }

    menu.findItem(R.id.ic_action_view_source).setVisible(true);
    menu.findItem(R.id.ic_action_vector_permalink).setVisible(true);

    if (!TextUtils.isEmpty(textMsg)) {
        menu.findItem(R.id.ic_action_vector_copy).setVisible(true);
        menu.findItem(R.id.ic_action_vector_quote).setVisible(true);
    }

    if (event.isUploadingMedias(mMediasCache)) {
        menu.findItem(R.id.ic_action_vector_cancel_upload).setVisible(true);
    }

    if (event.isDownloadingMedias(mMediasCache)) {
        menu.findItem(R.id.ic_action_vector_cancel_download).setVisible(true);
    }

    if (event.canBeResent()) {
        menu.findItem(R.id.ic_action_vector_resend_message).setVisible(true);

        if (event.isUndeliverable()) {
            menu.findItem(R.id.ic_action_vector_redact_message).setVisible(true);
        }
    } else if (event.mSentState == Event.SentState.SENT) {

        // test if the event can be redacted
        boolean canBeRedacted = !mIsPreviewMode;

        if (canBeRedacted) {
            // oneself message -> can redact it
            if (TextUtils.equals(event.sender, mSession.getMyUserId())) {
                canBeRedacted = true;
            } else {
                // need the mininum power level to redact an event
                Room room = mSession.getDataHandler().getRoom(event.roomId);

                if ((null != room) && (null != room.getLiveState().getPowerLevels())) {
                    PowerLevels powerLevels = room.getLiveState().getPowerLevels();
                    canBeRedacted = powerLevels.getUserPowerLevel(mSession.getMyUserId()) >= powerLevels.redact;
                }
            }
        }

        menu.findItem(R.id.ic_action_vector_redact_message).setVisible(canBeRedacted);

        if (Event.EVENT_TYPE_MESSAGE.equals(event.type)) {
            Message message = JsonUtils.toMessage(event.getContentAsJsonObject());

            // share / forward the message
            menu.findItem(R.id.ic_action_vector_share).setVisible(true);
            menu.findItem(R.id.ic_action_vector_forward).setVisible(true);

            // save the media in the downloads directory
            if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || Message.MSGTYPE_VIDEO.equals(message.msgtype)
                    || Message.MSGTYPE_FILE.equals(message.msgtype)) {
                menu.findItem(R.id.ic_action_vector_save).setVisible(true);
            }

            // offer to report a message content
            menu.findItem(R.id.ic_action_vector_report)
                    .setVisible(!mIsPreviewMode && !TextUtils.equals(event.sender, mSession.getMyUserId()));
        }

    }

    // display the menu
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(final MenuItem item) {
            // warn the listener
            if (null != mVectorMessagesAdapterEventsListener) {
                mVectorMessagesAdapterEventsListener.onEventAction(event, textMsg, item.getItemId());
            }

            // disable the selection
            mHighlightedEventId = null;
            notifyDataSetChanged();

            return true;
        }
    });

    popup.show();
}

From source file:com.google.android.apps.santatracker.presentquest.MapsActivity.java

private void initializeDebugUI() {
    if (!isDebug()) {
        return;/*from   w w w  .j a  va 2s . co m*/
    }

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_debug);
    fab.setVisibility(View.VISIBLE);

    final PopupMenu popup = new PopupMenu(this, fab);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.menu_debug_popup, popup.getMenu());

    // Show the menu when clicked
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popup.show();
        }
    });

    // Handle debug menu clicks
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            final int id = item.getItemId();
            if (id == R.id.item_drop_present) {
                // This should be about 20m away, so within the action radius
                LatLng fuzzyCurrent = FuzzyLocationUtil.fuzz(mCurrentLatLng);
                addPresent(fuzzyCurrent, true);
            }

            if (id == R.id.item_delete_present) {
                if (!mPresents.isEmpty()) {
                    deletePresent(mPresents.get(0));
                    drawMarkers();
                    drawMarkerLabels();
                }
            }

            if (id == R.id.item_play_jetpack) {
                showPlayJetpackDialog(null);
            }

            if (id == R.id.item_play_present_toss) {
                showPlayWorkshopDialog();
            }

            if (id == R.id.item_collect_20) {
                onPresentsCollected(20);
            }

            if (id == R.id.item_return) {
                onPresentsReturned(3);
            }

            if (id == R.id.item_downlevel) {
                mUser.downlevel();
                setUserProgress();
            }

            if (id == R.id.reset_prefs) {
                // Reset prefs
                mPreferences.resetAll();

                // Reset user
                mUser.presentsCollected = 0;
                mUser.presentsReturned = 0;
                mUser.save();

                // Delete all workshops
                Workshop.deleteAll(Workshop.class);

                // Delete all places and presents
                Present.deleteAll(Present.class);
                Place.deleteAll(Place.class);

                // Restart the activity
                recreate();
            }

            return true;
        }
    });
}

From source file:im.neon.adapters.VectorMessagesAdapter.java

/**
 * The user taps on the action icon./*from   www  .ja v  a 2s .c o m*/
 * @param event the selected event.
 * @param textMsg the event text
 * @param anchorView the popup anchor.
 */
@SuppressLint("NewApi")
private void onMessageClick(final Event event, final String textMsg, final View anchorView) {
    final PopupMenu popup = (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            ? new PopupMenu(mContext, anchorView, Gravity.END)
            : new PopupMenu(mContext, anchorView);

    popup.getMenuInflater().inflate(R.menu.vector_room_message_settings, popup.getMenu());

    // force to display the icons
    try {
        Field[] fields = popup.getClass().getDeclaredFields();
        for (Field field : fields) {
            if ("mPopup".equals(field.getName())) {
                field.setAccessible(true);
                Object menuPopupHelper = field.get(popup);
                Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
                Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
                setForceIcons.invoke(menuPopupHelper, true);
                break;
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "onMessageClick : force to display the icons failed " + e.getLocalizedMessage());
    }

    Menu menu = popup.getMenu();

    // hide entries
    for (int i = 0; i < menu.size(); i++) {
        menu.getItem(i).setVisible(false);
    }

    menu.findItem(R.id.ic_action_view_source).setVisible(true);
    menu.findItem(R.id.ic_action_vector_permalink).setVisible(true);

    if (!TextUtils.isEmpty(textMsg)) {
        menu.findItem(R.id.ic_action_vector_copy).setVisible(true);
        menu.findItem(R.id.ic_action_vector_quote).setVisible(true);
    }

    if (event.isUploadingMedias(mMediasCache)) {
        menu.findItem(R.id.ic_action_vector_cancel_upload).setVisible(true);
    }

    if (event.isDownloadingMedias(mMediasCache)) {
        menu.findItem(R.id.ic_action_vector_cancel_download).setVisible(true);
    }

    if (event.canBeResent()) {
        menu.findItem(R.id.ic_action_vector_resend_message).setVisible(true);

        if (event.isUndeliverable() || event.isUnkownDevice()) {
            menu.findItem(R.id.ic_action_vector_redact_message).setVisible(true);
        }
    } else if (event.mSentState == Event.SentState.SENT) {

        // test if the event can be redacted
        boolean canBeRedacted = !mIsPreviewMode
                && !TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION);

        if (canBeRedacted) {
            // oneself message -> can redact it
            if (TextUtils.equals(event.sender, mSession.getMyUserId())) {
                canBeRedacted = true;
            } else {
                // need the mininum power level to redact an event
                Room room = mSession.getDataHandler().getRoom(event.roomId);

                if ((null != room) && (null != room.getLiveState().getPowerLevels())) {
                    PowerLevels powerLevels = room.getLiveState().getPowerLevels();
                    canBeRedacted = powerLevels.getUserPowerLevel(mSession.getMyUserId()) >= powerLevels.redact;
                }
            }
        }

        menu.findItem(R.id.ic_action_vector_redact_message).setVisible(canBeRedacted);

        if (Event.EVENT_TYPE_MESSAGE.equals(event.getType())) {
            Message message = JsonUtils.toMessage(event.getContentAsJsonObject());

            // share / forward the message
            menu.findItem(R.id.ic_action_vector_share).setVisible(true);
            menu.findItem(R.id.ic_action_vector_forward).setVisible(true);

            // save the media in the downloads directory
            if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || Message.MSGTYPE_VIDEO.equals(message.msgtype)
                    || Message.MSGTYPE_FILE.equals(message.msgtype)) {
                menu.findItem(R.id.ic_action_vector_save).setVisible(true);
            }

            // offer to report a message content
            menu.findItem(R.id.ic_action_vector_report)
                    .setVisible(!mIsPreviewMode && !TextUtils.equals(event.sender, mSession.getMyUserId()));
        }

    }

    // e2e
    menu.findItem(R.id.ic_action_device_verification).setVisible(mE2eIconByEventId.containsKey(event.eventId));

    // display the menu
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(final MenuItem item) {
            // warn the listener
            if (null != mVectorMessagesAdapterEventsListener) {
                mVectorMessagesAdapterEventsListener.onEventAction(event, textMsg, item.getItemId());
            }

            // disable the selection
            mHighlightedEventId = null;
            notifyDataSetChanged();

            return true;
        }
    });

    // fix an issue reported by GA
    try {
        popup.show();
    } catch (Exception e) {
        Log.e(LOG_TAG, " popup.show failed " + e.getMessage());
    }
}

From source file:com.msopentech.applicationgateway.EnterpriseBrowserActivity.java

public void showSettingsPopup(View v) {
    try {//from ww w  .  ja v a2  s.  co m
        PopupMenu popup = new PopupMenu(this, v);
        MenuInflater inflater = popup.getMenuInflater();
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.menu_connection: {
                    showAgentsList();
                    return true;
                }
                case R.id.menu_sign_in_or_out: {
                    if (mIsSigninRequired) {
                        // Menu item in sign in mode.
                        //TODO: 
                        showSignIn(null, true);
                        return true;
                    }

                    // Clean up the session.
                    mTraits.sessionID = null;
                    mTraits.token = null;
                    mTraits.agent = null;

                    // Indicate the condition.
                    mIsSigninRequired = true;

                    //Remove all tabs except one.
                    mCustomTabHost.resetTabs();

                    mUrlEditTextView.setText("");

                    mProgressBarView.setProgress(0);

                    // Disable the reload button and set the right image for it.
                    mReloadButtonView.setEnabled(false);
                    mReloadButtonView.setImageResource(R.drawable.reload_button);

                    mStatusButtonView.setImageResource(R.drawable.connection_red);

                    // Since it's the user's intention to sign out, his
                    // history must be dropped.
                    PersistenceManager.dropContent(PersistenceManager.ContentType.HISTORY);

                    return true;
                }
                // Removed from RELEASE version. Should be active for development ONLY.                       
                //                        case R.id.menu_advanced_router_settings: {
                //                            showAdvancedRouterSettings(null);
                //                        }
                default: {
                    return false;
                }
                }
            }
        });
        inflater.inflate(R.menu.settings_menu, popup.getMenu());

        if (mIsSigninRequired) {
            MenuItem signItem = popup.getMenu().findItem(R.id.menu_sign_in_or_out);
            signItem.setTitle(getResources().getString(R.string.browser_menu_item_sign_in));
        }

        // Assumes that agent always has a display name. If display name is not present agent is considered to be not connected.
        MenuItem agentItem = popup.getMenu().findItem(R.id.menu_connection);
        String status = getResources().getString(R.string.browser_menu_item_choose_connection_not_connected);
        if (mTraits != null && mTraits.agent != null && !TextUtils.isEmpty(mTraits.agent.getDisplayName())) {
            status = mTraits.agent.getDisplayName();
        }
        Spannable span = new SpannableString(
                getResources().getString(R.string.browser_menu_item_choose_connection, status));
        span.setSpan(new RelativeSizeSpan(0.8f), 18, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.GRAY), 18, span.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        agentItem.setTitle(span);

        popup.show();
    } catch (final Exception e) {
        Utility.showAlertDialog(EnterpriseBrowserActivity.class.getSimpleName()
                + ".showSettingsPopup(): Failed. " + e.toString(), EnterpriseBrowserActivity.this);
    }
}

From source file:com.simadanesh.isatis.ScreenSlideActivity.java

private void showfilterMenu() {
    View p = findViewById(R.id.anchorer);
    progressbar.setVisibility(View.GONE);

    final PopupMenu popup = new PopupMenu(this, p);
    //Inflating the Popup using xml file  
    popup.getMenuInflater().inflate(R.menu.filter, popup.getMenu());
    for (int i = 0; i < popup.getMenu().size(); i++) {
        MenuItem item = popup.getMenu().getItem(i);
        String countstr = "0";
        switch (item.getItemId()) {
        case R.id.filter_no_filter:
            countstr = countFilterNofilter();
            break;
        case R.id.filter_no_data:
            countstr = countFilterNodata();
            break;
        case R.id.filter_valid_reading:
            countstr = countFilterValid();
            break;
        case R.id.filter_hilow:
            countstr = countFilterHilow();
            break;
        case R.id.filter_maneh:
            countstr = countFilterManeh();

            break;
        case R.id.filter_inspection:
            countstr = countFilterInspection();
            break;
        case R.id.filter_register_field:
            countstr = countFilterRegisterField();
            break;
        case R.id.filter_not_register_field:
            countstr = countFilterRegisterNotField();
            break;

        }/*from w w  w  .jav a  2 s.  c o  m*/
        item.setTitle(item.getTitle() + "\t" + countstr);
    }

    //registering popup with OnMenuItemClickListener  
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.filter_no_filter:
                filterNofilter();
                break;
            case R.id.filter_no_data:
                filterNodata();
                break;
            case R.id.filter_valid_reading:
                filterValid();
                break;
            case R.id.filter_hilow:
                filterHilow();
                break;
            case R.id.filter_maneh:
                //filterManeh();
                showManehMenu();
                break;
            case R.id.filter_inspection:
                filterInspection();
                break;
            case R.id.filter_register_field:
                filterRegisterField();
                break;
            case R.id.filter_not_register_field:
                filterRegisterNotField();
                break;

            }
            return true;
        }
    });

    final Handler handler1 = new Handler();
    progressbar.setVisibility(View.GONE);
    //android.R.attr.progressBarStyleLarge
    handler1.postDelayed(new Runnable() {
        @Override
        public void run() {
            popup.show();
        }
    }, 100);
}

From source file:com.example.search.car.pools.welcome.java

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Fragment fragment = null;// www  . ja v a  2 s .c o m
    if ((v.equals(l_1) || (v.equals(sp_city)))) {
        String[] city = { "Delhi/NCR", "Bengaluru", "Kolkata", "Mumbai", "Pune", "Ahmedabad" };
        dialog("City", city, sp_city);
    } else if ((v.equals(l_2) || (v.equals(sp_category)))) {
        String[] category = { "All", "Carpool", "Cab", "Rideshare" };
        dialog("Category", category, sp_category);
    } else if ((v.equals(l_3) || (v.equals(sp_search_for)))) {
        String[] search_for = { "Seeker", "Provider", "Both" };
        dialog(" Search For", search_for, sp_search_for);
    } else if (v.equals(close)) {
        promptsView.dismiss();
    } else if (v.equals(rlCities)) {
        layout = "Cities";
        fragment = new Cities();
        frag_tag = "Cities";
        set_fragment(fragment);
        mDrawerLayout.closeDrawer(mDrawerList);
        // getActionBar().setTitle("Cities");
        svg_cities = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.city1);
        iv_cities.setImageDrawable(svg_cities.createPictureDrawable());
        rlCities.setBackgroundColor(Color.parseColor("#00ca98"));
        l_cities.setBackground(getResources().getDrawable(R.drawable.white_circle_side_menu));

        svg_dashboard = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.dashboard);
        iv_dashboard.setImageDrawable(svg_dashboard.createPictureDrawable());
        rlDashboard.setBackgroundColor(Color.parseColor("#2C3E50"));
        l_dashboard.setBackground(getResources().getDrawable(R.drawable.search_blue));
        svg_search = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.search);
        iv_search.setImageDrawable(svg_search.createPictureDrawable());
        rlSearch.setBackgroundColor(Color.parseColor("#2C3E50"));
        l_search.setBackground(getResources().getDrawable(R.drawable.search_blue));
    } else if (v.equals(rlDashboard)) {
        if (task.getString("user_id", null) != null) {
            //            layout = "Dashboard";
            //            fragment = new dashboard();
            //            frag_tag = "Dashboard";
            //            // getActionBar().setTitle("My Profile");
            //            set_fragment(fragment);
            //            mDrawerLayout.closeDrawer(mDrawerList);
            //            svg_dashboard = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.dashboard1);
            //            iv_dashboard.setImageDrawable(svg_dashboard.createPictureDrawable());
            //            rlDashboard.setBackgroundColor(Color.parseColor("#00ca98"));
            //            l_dashboard.setBackground(getResources().getDrawable(R.drawable.white_circle_side_menu));
            //
            //            svg_cities = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.city);
            //            iv_cities.setImageDrawable(svg_cities.createPictureDrawable());
            //            rlCities.setBackgroundColor(Color.parseColor("#2C3E50"));
            //            l_cities.setBackground(getResources().getDrawable(R.drawable.search_blue));
            //            svg_search = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.search);
            //            iv_search.setImageDrawable(svg_search.createPictureDrawable());
            //            rlSearch.setBackgroundColor(Color.parseColor("#2C3E50"));
            //            l_search.setBackground(getResources().getDrawable(R.drawable.search_blue));
            Intent i = new Intent(welcome.this, dashboard_main.class);
            i.putExtra("edit", "1");
            startActivity(i);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            Toast.makeText(welcome.this, "Please Login First", Toast.LENGTH_SHORT).show();
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    } else if (v.equals(rlSearch)) {
        layout = "Search";
        frag_tag = "Search";
        fragment = new Search();
        set_fragment(fragment);
        mDrawerLayout.closeDrawer(mDrawerList);
        // getActionBar().setTitle("Search");

        svg_search = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.search1);
        iv_search.setImageDrawable(svg_search.createPictureDrawable());
        rlSearch.setBackgroundColor(Color.parseColor("#00ca98"));
        l_search.setBackground(getResources().getDrawable(R.drawable.white_circle_side_menu));

        svg_dashboard = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.dashboard);
        iv_dashboard.setImageDrawable(svg_dashboard.createPictureDrawable());
        rlDashboard.setBackgroundColor(Color.parseColor("#2C3E50"));
        l_dashboard.setBackground(getResources().getDrawable(R.drawable.search_blue));
        svg_cities = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.city);
        iv_cities.setImageDrawable(svg_cities.createPictureDrawable());
        rlCities.setBackgroundColor(Color.parseColor("#2C3E50"));
        l_cities.setBackground(getResources().getDrawable(R.drawable.search_blue));
    } else if (v.equals(rlProfile_login) || v.equals(profile_login)) {
        if (task.getString("user_id", null) == null) {
            Intent i = new Intent(getBaseContext(), user_login.class);
            i.putExtra("frag_id", frag_id);
            startActivity(i);
        }
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    //      else if (v.equals(rlEditProfile)) {
    //         if (task.getString("user_id", null) != null) {
    //            Intent i = new Intent(welcome.this, dashboard_main.class);
    //            i.putExtra("edit", "3");
    //            startActivity(i);
    //         } else {
    //            Toast.makeText(welcome.this, "Please Login First", Toast.LENGTH_SHORT).show();
    //         }
    //         mDrawerLayout.closeDrawer(mDrawerList);
    //      } 
    else if (v.equals(login) || v.equals(rlLogin)) {
        if (task.getString("user_id", null) != null && login.getText().toString().contentEquals("Logout")) {
            SharedPreferences.Editor editor = getSharedPreferences("user", MODE_PRIVATE).edit();
            editor.clear();
            editor.commit();
            login.setText("Login");
            rlDashboard.setVisibility(View.GONE);
            //            rlEditProfile.setVisibility(View.GONE);

            if (layout.contentEquals("Dashboard") || frag_tag.contentEquals("Dashboard")) {
                // highlight search menu on slider during on resume
                // change fragment to search
                FragmentManager fm = getFragmentManager();
                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                fragmentTransaction.replace(R.id.content_frame, new Search());
                fragmentTransaction.commit();
                svg_search = SVGParser.getSVGFromResource(welcome.this.getResources(), R.raw.search1);
                iv_search.setImageDrawable(svg_search.createPictureDrawable());
                rlSearch.setBackgroundColor(Color.parseColor("#00ca98"));
                l_search.setBackground(getResources().getDrawable(R.drawable.white_circle_side_menu));
            }

            iv_login.setImageDrawable(svg_login.createPictureDrawable());
            rlProfile.setVisibility(View.GONE);
            rlProfile_login.setVisibility(View.VISIBLE);
            if (frag_id == 6) {
                Intent i_user = new Intent(getBaseContext(), user_login.class);
                i_user.putExtra("frag_id", frag_id);
                startActivity(i_user);
            }
        } else {
            Intent i = new Intent(getBaseContext(), user_login.class);
            i.putExtra("frag_id", frag_id);
            startActivity(i);
        }
        mDrawerLayout.closeDrawer(mDrawerList);
    } else if (v.equals(b_search)) {
        if (sp_city.getText().toString().toUpperCase().equals("SELECT CITY")) {
            Toast.makeText(welcome.this, "First Select the City", Toast.LENGTH_LONG).show();
        } else {
            Intent i = new Intent(welcome.this, search_result.class);
            i.putExtra("city", sp_city.getText().toString());
            i.putExtra("category", sp_category.getText().toString());
            i.putExtra("search_for", sp_search_for.getText().toString());
            i.putExtra("from", et_from.getText().toString());
            i.putExtra("to", et_to.getText().toString());
            i.putExtra("frag_id", 1);
            i.putExtra("company_id", 0);

            startActivity(i);
            promptsView.dismiss();
        }
    } else if (v.equals(l_nav_search) || v.equals(ib_search)) {
        final int DELAY = 200;
        // ColorDrawable f = new
        // ColorDrawable(Color.parseColor("#0087ca"));
        // ColorDrawable f1 = new
        // ColorDrawable(Color.parseColor("#3398ca"));
        AnimationDrawable a = new AnimationDrawable();
        a.addFrame(d1, DELAY);
        a.addFrame(d2, DELAY);
        a.setOneShot(true);
        l_nav_search.setBackground(a);
        a.start();
        showSearchDialog();
    } else if (v.equals(l_handle) || v.equals(ib_handle)) {
        final int DELAY = 200;
        // ColorDrawable f = new
        // ColorDrawable(Color.parseColor("#0087ca"));
        // ColorDrawable f1 = new
        // ColorDrawable(Color.parseColor("#3398ca"));

        AnimationDrawable a = new AnimationDrawable();
        a.addFrame(d1, DELAY);
        a.addFrame(d2, DELAY);
        a.setOneShot(true);
        l_handle.setBackground(a);
        a.start();
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            mDrawerLayout.openDrawer(mDrawerList);
        }
    } else if (v.equals(l_menu) || v.equals(ib_menu)) {
        final int DELAY = 200;
        // for light background
        // ColorDrawable f = new
        // ColorDrawable(Color.parseColor("#0087ca"));
        // ColorDrawable f1 = new
        // ColorDrawable(Color.parseColor("#3398ca"));
        AnimationDrawable a = new AnimationDrawable();
        a.addFrame(d1, DELAY);
        a.addFrame(d2, DELAY);
        a.setOneShot(true);
        l_menu.setBackground(a);
        a.start();

        final PopupMenu popup = new PopupMenu(welcome.this, v);
        popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());

        bedMenuItem = popup.getMenu().findItem(R.id.menu_login);
        final SharedPreferences task = getSharedPreferences("user", MODE_PRIVATE);
        popup.getMenu().findItem(R.id.menu_add_new_list).setVisible(!(task.getString("user_id", null) == null));
        popup.getMenu().findItem(R.id.menu_dashboard).setVisible(!(task.getString("user_id", null) == null));

        if (task.getString("user_id", null) != null) {
            bedMenuItem.setTitle("Logout");
            login.setText("Logout");
            iv_login.setImageDrawable(svg_logout.createPictureDrawable());
            rlProfile.setVisibility(View.VISIBLE);
            rlProfile_login.setVisibility(View.GONE);
            rlDashboard.setVisibility(View.VISIBLE);
            //            rlEditProfile.setVisibility(View.VISIBLE);
            set_data();
        } else {
            bedMenuItem.setTitle("Login/Register");
            login.setText("Login");
            iv_login.setImageDrawable(svg_login.createPictureDrawable());
            rlDashboard.setVisibility(View.GONE);
            //            rlEditProfile.setVisibility(View.GONE);
            rlProfile.setVisibility(View.GONE);
            rlProfile_login.setVisibility(View.VISIBLE);
        }

        if (task.getString("user_id", null) != null) {
            popup.getMenu().findItem(R.id.menu_login).setTitle("Logout");
        } else {
            popup.getMenu().findItem(R.id.menu_login).setTitle("Login/Register");
        }
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // TODO Auto-generated method stub
                int id = item.getItemId();
                Intent i;
                switch (id) {
                case R.id.menu_add_new_list:
                    if (task.getString("user_id", null) != null) {
                        i = new Intent(welcome.this, create_activity.class);
                        startActivity(i);
                    } else {
                        Toast.makeText(welcome.this, "Login first", Toast.LENGTH_SHORT).show();
                    }

                    return true;
                case R.id.menu_dashboard:
                    if (task.getString("user_id", null) != null) {
                        i = new Intent(welcome.this, dashboard_main.class);
                        i.putExtra("edit", "12344");
                        startActivity(i);
                    } else {
                        Toast.makeText(welcome.this, "Please Login first", Toast.LENGTH_LONG).show();
                    }
                    return true;
                case R.id.menu_login:
                    if (bedMenuItem.getTitle().equals("Logout")) {
                        SharedPreferences.Editor editor = getSharedPreferences("user", MODE_PRIVATE).edit();
                        editor.clear();
                        editor.commit();
                        // bedMenuItem.setTitle("Login/Register");
                        login.setText("Login");
                        rlDashboard.setVisibility(View.GONE);
                        //                     rlEditProfile.setVisibility(View.GONE);

                        if (layout.contentEquals("Dashboard") || frag_tag.contentEquals("Dashboard")) {
                            // highlight search menu on slider during on
                            // resume
                            // change fragment to search
                            FragmentManager fm = getFragmentManager();
                            FragmentTransaction fragmentTransaction = fm.beginTransaction();
                            fragmentTransaction.replace(R.id.content_frame, new Search());
                            fragmentTransaction.commit();
                            SVG svg_search = SVGParser.getSVGFromResource(welcome.this.getResources(),
                                    R.raw.search1);
                            iv_search.setImageDrawable(svg_search.createPictureDrawable());
                            rlSearch.setBackgroundColor(Color.parseColor("#00ca98"));
                            l_search.setBackground(
                                    getResources().getDrawable(R.drawable.white_circle_side_menu));
                        }

                        iv_login.setImageDrawable(svg_login.createPictureDrawable());
                        rlProfile.setVisibility(View.GONE);
                        rlProfile_login.setVisibility(View.VISIBLE);
                        if (frag_id == 6) {
                            Intent i_user = new Intent(getBaseContext(), user_login.class);
                            i_user.putExtra("frag_id", frag_id);
                            startActivity(i_user);
                        }
                    } else {
                        i = new Intent(getBaseContext(), user_login.class);
                        i.putExtra("frag_id", frag_id);
                        startActivity(i);
                    }
                    return true;
                }
                return false;
            }
        });
        popup.show();
        // } else {
        // openOptionsMenu();
        // }
    }

}

From source file:freed.viewer.gridview.GridViewFragment.java

private void showFileSelectionPopup(View v) {
    PopupMenu popup = new PopupMenu(getContext(), v);
    popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override//from www.j a  va  2s  .  co  m
        public boolean onMenuItemClick(MenuItem item) {
            int i = item.getItemId();
            if (i == id.all) {
                filetypeButton.setText(string.ALL);
                formatsToShow = FormatTypes.all;
            } else if (i == id.raw) {
                filetypeButton.setText("RAW");
                formatsToShow = FormatTypes.raw;
            } else if (i == id.bayer) {
                filetypeButton.setText("BAYER");
                formatsToShow = FormatTypes.raw;
            } else if (i == id.dng) {
                filetypeButton.setText("DNG");
                formatsToShow = FormatTypes.dng;
            } else if (i == id.jps) {
                filetypeButton.setText("JPS");
                formatsToShow = FormatTypes.jps;
            } else if (i == id.jpg) {
                filetypeButton.setText("JPG");
                formatsToShow = FormatTypes.jpg;
            } else if (i == id.mp4) {
                filetypeButton.setText("MP4");
                formatsToShow = FormatTypes.mp4;
            }
            //if (savedInstanceFilePath != null)
            viewerActivityInterface.LoadFolder(folderToShow, formatsToShow);

            return false;

        }
    });
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(menu.filetypepopupmenu, popup.getMenu());
    popup.show();
}

From source file:org.brandroid.openmanager.fragments.ContentFragment.java

public boolean createContextMenu(final OpenPath file, final AdapterView<?> list, final View view, final int pos,
        final int xOffset, final int yOffset) {
    Logger.LogInfo(getClassName() + ".onItemLongClick: " + file);

    final OpenContextMenuInfo info = new OpenContextMenuInfo(file);

    if (!OpenExplorer.USE_PRETTY_CONTEXT_MENUS) {
        if (Build.VERSION.SDK_INT > 10) {
            final PopupMenu pop = new PopupMenu(view.getContext(), view);
            pop.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    if (onOptionsItemSelected(item)) {
                        pop.dismiss();//from w  ww . ja  v  a2  s.c om
                        return true;
                    } else if (getExplorer() != null)
                        return getExplorer().onIconContextItemSelected(pop, item, item.getMenuInfo(), view);
                    return false;
                }
            });
            pop.getMenuInflater().inflate(R.menu.context_file, pop.getMenu());
            onPrepareOptionsMenu(pop.getMenu());
            if (DEBUG)
                Logger.LogDebug("PopupMenu.show()");
            pop.show();
            return true;
        } else
            return list.showContextMenu();
    } else if (OpenExplorer.BEFORE_HONEYCOMB || !OpenExplorer.USE_ACTIONMODE) {

        try {
            //View anchor = view; //view.findViewById(R.id.content_context_helper);
            //if(anchor == null) anchor = view;
            //view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            //Rect r = new Rect(view.getLeft(),view.getTop(),view.getMeasuredWidth(),view.getMeasuredHeight());
            MenuBuilder cmm = IconContextMenu.newMenu(list.getContext(), R.menu.context_file);
            if (!file.canRead()) {
                MenuUtils.setMenuEnabled(cmm, false);
                MenuUtils.setMenuEnabled(cmm, true, R.id.menu_context_info);
            }
            MenuUtils.setMenuEnabled(cmm, file.canWrite(), R.id.menu_context_paste, R.id.menu_context_cut,
                    R.id.menu_context_delete, R.id.menu_context_rename);
            onPrepareOptionsMenu(cmm);

            //if(!file.isArchive()) hideItem(cmm, R.id.menu_context_unzip);
            if (getClipboard().size() > 0)
                MenuUtils.setMenuVisible(cmm, false, R.id.menu_multi);
            else
                MenuUtils.setMenuVisible(cmm, false, R.id.menu_context_paste);
            MenuUtils.setMenuEnabled(cmm, !file.isDirectory(), R.id.menu_context_edit, R.id.menu_context_view);
            final IconContextMenu cm = new IconContextMenu(list.getContext(), cmm, view);
            //cm.setAnchor(anchor);
            cm.setNumColumns(2);
            cm.setOnIconContextItemSelectedListener(getExplorer());
            cm.setInfo(info);
            cm.setTextLayout(R.layout.context_item);
            cm.setTitle(file.getName());
            if (!cm.show()) //r.left, r.top);
                return list.showContextMenu();
            else
                return true;
        } catch (Exception e) {
            Logger.LogWarning("Couldn't show Iconified menu.", e);
            return list.showContextMenu();
        }
    }

    if (!OpenExplorer.BEFORE_HONEYCOMB && OpenExplorer.USE_ACTIONMODE) {
        if (!file.isDirectory() && mActionMode == null && !getClipboard().isMultiselect()) {
            try {
                Method mStarter = getActivity().getClass().getMethod("startActionMode");
                mActionMode = mStarter.invoke(getActivity(), new ActionModeHelper.Callback() {
                    //@Override
                    public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
                        return false;
                    }

                    //@Override
                    public void onDestroyActionMode(android.view.ActionMode mode) {
                        mActionMode = null;
                        mActionModeSelected = false;
                    }

                    //@Override
                    public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
                        mode.getMenuInflater().inflate(R.menu.context_file, menu);

                        mActionModeSelected = true;
                        return true;
                    }

                    //@Override
                    public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
                        //ArrayList<OpenPath> files = new ArrayList<OpenPath>();

                        //OpenPath file = mLastPath.getChild(mode.getTitle().toString());
                        //files.add(file);

                        if (item.getItemId() != R.id.menu_context_cut && item.getItemId() != R.id.menu_multi
                                && item.getItemId() != R.id.menu_context_copy) {
                            mode.finish();
                            mActionModeSelected = false;
                        }
                        return executeMenu(item.getItemId(), mode, file);
                    }
                });
                Class cAM = Class.forName("android.view.ActionMode");
                Method mST = cAM.getMethod("setTitle", CharSequence.class);
                mST.invoke(mActionMode, file.getName());
            } catch (Exception e) {
                Logger.LogError("Error using ActionMode", e);
            }
        }
        return true;

    }

    if (file.isDirectory() && mActionMode == null && !getClipboard().isMultiselect()) {
        if (!OpenExplorer.BEFORE_HONEYCOMB && OpenExplorer.USE_ACTIONMODE) {
            try {
                Method mStarter = getActivity().getClass().getMethod("startActionMode");
                mActionMode = mStarter.invoke(getActivity(), new ActionModeHelper.Callback() {

                    //@Override
                    public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
                        return false;
                    }

                    //@Override
                    public void onDestroyActionMode(android.view.ActionMode mode) {
                        mActionMode = null;
                        mActionModeSelected = false;
                    }

                    //@Override
                    public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
                        mode.getMenuInflater().inflate(R.menu.context_file, menu);
                        menu.findItem(R.id.menu_context_paste).setEnabled(getClipboard().size() > 0);
                        //menu.findItem(R.id.menu_context_unzip).setEnabled(mHoldingZip);

                        mActionModeSelected = true;

                        return true;
                    }

                    //@Override
                    public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
                        return executeMenu(item.getItemId(), mode, file);
                    }
                });
                Class cAM = Class.forName("android.view.ActionMode");
                Method mST = cAM.getMethod("setTitle", CharSequence.class);
                mST.invoke(mActionMode, file.getName());
            } catch (Exception e) {
                Logger.LogError("Error using ActionMode", e);
            }
        }

        return true;
    }

    return false;
}

From source file:org.thecongers.mcluster.MainActivity.java

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

    // Keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);//  w  w  w  . j  a va2  s.  com

    View myView = findViewById(R.id.layoutApp);
    root = myView.getRootView();
    layoutIcons = (LinearLayout) findViewById(R.id.layoutIcons);
    layoutMiddleLeft = (LinearLayout) findViewById(R.id.layoutMiddleLeft);
    layoutMiddleRight = (LinearLayout) findViewById(R.id.layoutMiddleRight);
    layoutBottomLeft = (LinearLayout) findViewById(R.id.layoutBottomLeft);
    layoutBottomRight = (LinearLayout) findViewById(R.id.layoutBottomRight);
    imageKillSwitch = (ImageView) findViewById(R.id.imageViewKillSwitch);
    imageLeftArrow = (ImageView) findViewById(R.id.imageViewLeftArrow);
    imageRightArrow = (ImageView) findViewById(R.id.imageViewRightArrow);
    imageHighBeam = (ImageView) findViewById(R.id.imageViewHighBeam);
    imageHeatedGrips = (ImageView) findViewById(R.id.imageViewHeatedGrips);
    imageABS = (ImageView) findViewById(R.id.imageViewABS);
    imageLampf = (ImageView) findViewById(R.id.imageViewLampf);
    imageFuelWarning = (ImageView) findViewById(R.id.imageViewFuelWarning);
    imageFuelLevel = (ImageView) findViewById(R.id.imageViewFuelLevel);
    imageESA = (ImageView) findViewById(R.id.imageViewESA);
    txtSpeed = (TextView) findViewById(R.id.textViewSpeed);
    txtSpeedUnit = (TextView) findViewById(R.id.textViewSpeedUnit);
    txtGear = (TextView) findViewById(R.id.textViewGear);
    txtOdometers = (TextView) findViewById(R.id.textViewOdometer);
    txtESA = (TextView) findViewById(R.id.textViewESA);
    imageButtonTPMS = (ImageButton) findViewById(R.id.imageButtonTPMS);
    imageButtonBluetooth = (ImageButton) findViewById(R.id.imageButtonBluetooth);
    imageButtonPreference = (ImageButton) findViewById(R.id.imageButtonPreference);
    progressFuelLevel = (ProgressBar) findViewById(R.id.progressBarFuelLevel);

    // Backgrounds
    background = R.drawable.rectangle_bordered;
    backgroundDark = R.drawable.rectangle_bordered_dark;

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Update layout
    updateLayout();

    if (!sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        imageButtonTPMS.setImageResource(R.mipmap.blank_icon);
        imageButtonTPMS.setEnabled(false);
    } else {
        imageButtonTPMS.setImageResource(R.mipmap.tpms_off);
        imageButtonTPMS.setEnabled(true);
    }

    // Set initial color scheme
    updateColors();
    if (sharedPrefs.getBoolean("prefNightMode", false)) {
        imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
    }

    // Watch for Bluetooth Changes
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(btReceiver, filter1);
    this.registerReceiver(btReceiver, filter2);
    this.registerReceiver(btReceiver, filter3);

    // Setup Text To Speech
    text2speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                text2speech.setLanguage(Locale.US);
            }
        }
    });

    imageButtonBluetooth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            canBusConnect();
        }
    });

    imageButtonTPMS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
                iTPMSConnect();
            }
        }
    });

    imageButtonPreference.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(MainActivity.this, v);
            popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.action_settings:
                        // Settings Menu was selected
                        Intent i = new Intent(getApplicationContext(),
                                org.thecongers.mcluster.UserSettingActivity.class);
                        startActivityForResult(i, SETTINGS_RESULT);
                        return true;
                    case R.id.action_about:
                        // About was selected
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.alert_about_title));
                        builder.setMessage(readRawTextFile(MainActivity.this, R.raw.about));
                        builder.setPositiveButton(getResources().getString(R.string.alert_about_button), null);
                        builder.show();
                        return true;
                    case R.id.action_exit:
                        // Exit menu item was selected
                        if (logger != null) {
                            logger.shutdown();
                        }
                        finish();
                        System.exit(0);
                    default:
                        return true;
                    }
                }
            });

            popup.show();
        }
    });

    layoutMiddleRight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int infoViewCurr = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
            if (infoViewCurr < (numInfoViewLayouts - 1)) {
                infoViewCurr = infoViewCurr + 1;
            } else {
                infoViewCurr = 0;
            }
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString("prefInfoView", String.valueOf(infoViewCurr));
            editor.commit();

            //update layout
            updateLayout();
        }
    });

    canBusMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Check to see if message is the correct size
                if (msg.arg1 == 27) {
                    byte[] readBuf = (byte[]) msg.obj;
                    String message = new String(readBuf);

                    //Default Units
                    String speedUnit = "km/h";
                    String odometerUnit = "km";
                    String temperatureUnit = "C";

                    String[] splitMessage = message.split(",");
                    if (splitMessage[0].contains("10C")) {

                        //RPM
                        if (sharedPrefs.getString("prefInfoView", "0").contains("0")) {
                            int rpm = (Integer.parseInt(splitMessage[4], 16) * 255
                                    + Integer.parseInt(splitMessage[3], 16)) / 4;
                            txtInfo = (TextView) findViewById(R.id.textViewInfo);
                            txtInfo.setGravity(Gravity.CENTER | Gravity.BOTTOM);
                            txtInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
                            txtInfo.setText(Integer.toString(rpm) + " RPM");
                            if (rpm > 8500) {
                                txtInfo.setTextColor(getResources().getColor(R.color.red));
                            } else {
                                txtInfo.setTextColor(getResources().getColor(android.R.color.black));
                            }
                        }

                        //Kill Switch
                        String killSwitchValue = splitMessage[5].substring(1);
                        if (killSwitchValue.contains("5") || killSwitchValue.contains("9")) {
                            //Kill Switch On
                            imageKillSwitch.setImageResource(R.mipmap.kill_switch);
                        } else {
                            //Kill Switch Off
                            imageKillSwitch.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("130")) {
                        //Turn indicators
                        String indicatorValue = splitMessage[8];

                        if (indicatorValue.contains("D7")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        } else if (indicatorValue.contains("E7")) {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else if (indicatorValue.contains("EF")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        }

                        //High Beam
                        String highBeamValue = splitMessage[7].substring(1);
                        if (highBeamValue.contains("9")) {
                            //High Beam On
                            imageHighBeam.setImageResource(R.mipmap.high_beam);
                        } else {
                            //High Beam Off
                            imageHighBeam.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("294")) {
                        //Front Wheel Speed
                        double frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                + Integer.parseInt(splitMessage[3], 16)) * 0.063);
                        //If 21" Wheel
                        if (sharedPrefs.getString("prefDistance", "0").contains("1")) {
                            frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                    + Integer.parseInt(splitMessage[3], 16)) * 0.064);
                        }
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            speedUnit = "MPH";
                            frontSpeed = frontSpeed / 1.609344;
                        }
                        txtSpeed.setText(String.valueOf((int) Math.round(frontSpeed)));
                        txtSpeedUnit.setText(speedUnit);

                        //ABS
                        String absValue = splitMessage[2].substring(0, 1);
                        if (absValue.contains("B")) {
                            //ABS Off
                            imageABS.setImageResource(R.mipmap.abs);
                        } else {
                            //ABS On
                            imageABS.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("2BC")) {
                        //Engine Temperature
                        engineTempC = (Integer.parseInt(splitMessage[3], 16) * 0.75) - 24.0;

                        if (engineTempC >= 115.5) {
                            if (engineTempAlertTriggered == false) {
                                engineTempAlertTriggered = true;
                                speakString(getResources().getString(R.string.engine_temp_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            engineTempAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double engineTemp = engineTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                engineTemp = (int) Math.round((9.0 / 5.0) * engineTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtEngineTemp.setText(String.valueOf(engineTemp) + temperatureUnit);
                        }

                        // Gear
                        String gearValue = splitMessage[6].substring(0, 1);
                        String gear;
                        if (gearValue.contains("1")) {
                            gear = "1";
                        } else if (gearValue.contains("2")) {
                            gear = "N";
                        } else if (gearValue.contains("4")) {
                            gear = "2";
                        } else if (gearValue.contains("7")) {
                            gear = "3";
                        } else if (gearValue.contains("8")) {
                            gear = "4";
                        } else if (gearValue.contains("B")) {
                            gear = "5";
                        } else if (gearValue.contains("D")) {
                            gear = "6";
                        } else {
                            gear = "-";
                        }
                        txtGear.setText(gear);

                        //Air Temperature
                        airTempC = (Integer.parseInt(splitMessage[8], 16) * 0.75) - 48.0;
                        //Freeze Warning
                        if (airTempC <= 0.0) {
                            if (freezeAlertTriggered == false) {
                                freezeAlertTriggered = true;
                                speakString(getResources().getString(R.string.freeze_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            freezeAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double airTemp = airTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                airTemp = (int) Math.round((9.0 / 5.0) * airTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtAirTemp.setText(String.valueOf(airTemp) + temperatureUnit);
                        }

                    } else if (splitMessage[0].contains("2D0")) {
                        //Info Button
                        String infoButtonValue = splitMessage[6].substring(1);
                        if (infoButtonValue.contains("5")) {
                            //Short Press
                            if (!btnPressed) {
                                int infoButton = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
                                if (infoButton < (numInfoViewLayouts - 1)) {
                                    infoButton = infoButton + 1;
                                } else {
                                    infoButton = 0;
                                }
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(infoButton));
                                editor.commit();

                                //update layout
                                updateLayout();
                                btnPressed = true;
                            }
                        } else if (infoButtonValue.contains("6")) {
                            //Long Press
                        } else {
                            btnPressed = false;
                        }

                        //Heated Grips
                        String heatedGripSwitchValue = splitMessage[8].substring(0, 1);
                        if (heatedGripSwitchValue.contains("C")) {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        } else if (heatedGripSwitchValue.contains("D")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low_dark);
                            }
                        } else if (heatedGripSwitchValue.contains("E")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
                            }
                        } else {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        }

                        //ESA Damping and Preload
                        String esaDampingValue1 = splitMessage[5].substring(1);
                        String esaDampingValue2 = splitMessage[8].substring(1);
                        String esaPreLoadValue = splitMessage[5].substring(0, 1);
                        if (esaDampingValue1.contains("B") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaPreLoadValue.contains("1")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("3")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("4")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("6")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("7")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("8")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("9")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else {
                            txtESA.setText("");
                            imageESA.setImageResource(R.mipmap.blank_icon);
                        }

                        //Lamp Fault
                        //TODO: Display/speak Bulb location
                        String lampFaultValue = splitMessage[3].substring(0, 1);
                        if (lampFaultValue.contains("0")) {
                            //None
                            imageLampf.setImageResource(R.mipmap.blank_icon);
                        } else if (lampFaultValue.contains("1")) {
                            //Low Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("4")) {
                            //High Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("8")) {
                            //Signal Bulb
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else {
                            //Unknown
                            imageLampf.setImageResource(R.mipmap.lampf);
                        }

                        //Fuel Level
                        double fuelLevelPercent = ((Integer.parseInt(splitMessage[4], 16) - 73) / 182.0)
                                * 100.0;
                        progressFuelLevel.setProgress((int) Math.round(fuelLevelPercent));

                        //Fuel Level Warning
                        double fuelWarning = sharedPrefs.getInt("prefFuelWarning", 30);
                        if (fuelLevelPercent >= fuelWarning) {
                            imageFuelWarning.setImageResource(R.mipmap.blank_icon);
                            fuelAlertTriggered = false;
                            fuelReserveAlertTriggered = false;
                        } else if (fuelLevelPercent == 0) {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelReserveAlertTriggered) {
                                fuelReserveAlertTriggered = true;
                                //Audio Warning
                                speakString(getResources().getString(R.string.fuel_alert_reserve));
                            }
                        } else {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelAlertTriggered) {
                                fuelAlertTriggered = true;
                                //Audio Warning
                                String fuelAlert = getResources().getString(R.string.fuel_alert_begin)
                                        + String.valueOf((int) Math.round(fuelLevelPercent))
                                        + getResources().getString(R.string.fuel_alert_end);
                                speakString(fuelAlert);
                                //Suggest nearby fuel stations
                                if (!sharedPrefs.getString("prefFuelStation", "0").contains("0")) {
                                    // Display prompt to open google maps
                                    MainActivity.this.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                                    MainActivity.this);
                                            builder.setTitle(getResources()
                                                    .getString(R.string.alert_fuel_stations_title));
                                            if (sharedPrefs.getString("prefFuelStation", "0").contains("1")) {
                                                // Search for fuel stations nearby
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_suggestions));
                                            } else if (sharedPrefs.getString("prefFuelStation", "0")
                                                    .contains("2")) {
                                                // Route to nearest fuel station
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_navigation));
                                            }
                                            builder.setPositiveButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_positive),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Uri gmmIntentUri = null;
                                                            if (sharedPrefs.getString("prefFuelStation", "0")
                                                                    .contains("1")) {
                                                                // Search for fuel stations nearby
                                                                gmmIntentUri = Uri
                                                                        .parse("geo:0,0?q=gas+station");
                                                            } else if (sharedPrefs
                                                                    .getString("prefFuelStation", "0")
                                                                    .contains("2")) {
                                                                // Route to nearest fuel station
                                                                gmmIntentUri = Uri.parse(
                                                                        "google.navigation:q=gas+station");
                                                            }
                                                            Intent mapIntent = new Intent(Intent.ACTION_VIEW,
                                                                    gmmIntentUri);
                                                            mapIntent
                                                                    .setPackage("com.google.android.apps.maps");
                                                            startActivity(mapIntent);
                                                        }
                                                    });
                                            builder.setNegativeButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_negative),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int id) {
                                                            dialog.cancel();
                                                        }
                                                    });
                                            builder.show();
                                        }
                                    });
                                }
                            }
                        }
                    } else if (splitMessage[0].contains("3F8")) {
                        String odometerValue = "";
                        for (int i = 4; i > 1; i--) {
                            odometerValue = odometerValue + splitMessage[i];
                        }
                        double odometer = Integer.parseInt(odometerValue, 16);
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            odometerUnit = "Miles";
                            odometer = odometer * 0.6214;
                        }
                        txtOdometers.setText(String.valueOf((int) Math.round(odometer)) + " " + odometerUnit);
                    }
                    imageButtonBluetooth.setImageResource(R.mipmap.bluetooth_on);
                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                        // Log data
                        if (logger == null) {
                            logger = new LogData();
                        }
                        if (logger != null) {
                            logger.write(message);
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    sensorMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Message received
                Log.d(TAG, "iTPMS Message Received, Length: " + msg.arg1);
                // Check to see if message is the correct size
                if (msg.arg1 == 13) {
                    byte[] readBuf = (byte[]) msg.obj;

                    // Validate against checksum
                    int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8]
                            + readBuf[9] + readBuf[10];
                    if (calculatedCheckSum == readBuf[11]) {
                        // Convert to hex
                        String[] hexData = new String[13];
                        StringBuilder sbhex = new StringBuilder();
                        for (int i = 0; i < msg.arg1; i++) {
                            hexData[i] = String.format("%02X", readBuf[i]);
                            sbhex.append(hexData[i]);
                        }

                        // Get sensor position
                        String position = hexData[3];
                        // Get sensor ID
                        StringBuilder sensorID = new StringBuilder();
                        sensorID.append(hexData[4]);
                        sensorID.append(hexData[5]);
                        sensorID.append(hexData[6]);
                        sensorID.append(hexData[7]);

                        // Only parse message if there is one or more sensor mappings
                        String prefFrontID = sharedPrefs.getString("prefFrontID", "");
                        String prefRearID = sharedPrefs.getString("prefRearID", "");
                        try {
                            // Get temperature
                            int tempC = Integer.parseInt(hexData[8], 16) - 50;
                            double temp = tempC;
                            String temperatureUnit = "C";
                            // Get tire pressure
                            int psi = Integer.parseInt(hexData[9], 16);
                            double pressure = psi;
                            String pressureUnit = "psi";
                            // Get battery voltage
                            double voltage = Integer.parseInt(hexData[10], 16) / 50;
                            // Get pressure thresholds
                            int lowPressure = Integer.parseInt(sharedPrefs.getString("prefLowPressure", "30"));
                            int highPressure = Integer
                                    .parseInt(sharedPrefs.getString("prefHighPressure", "46"));
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                temp = (9.0 / 5.0) * tempC + 32.0;
                                temperatureUnit = "F";
                            }
                            int formattedTemperature = (int) (temp + 0.5d);
                            String pressureFormat = sharedPrefs.getString("prefPressureF", "0");
                            if (pressureFormat.contains("1")) {
                                // KPa
                                pressure = psi * 6.894757293168361;
                                pressureUnit = "KPa";
                            } else if (pressureFormat.contains("2")) {
                                // Kg-f
                                pressure = psi * 0.070306957965539;
                                pressureUnit = "Kg-f";
                            } else if (pressureFormat.contains("3")) {
                                // Bar
                                pressure = psi * 0.0689475729;
                                pressureUnit = "Bar";
                            }
                            int formattedPressure = (int) (pressure + 0.5d);
                            // Get checksum
                            String checksum = hexData[11];

                            if (Integer.parseInt(hexData[3], 16) <= 2) {
                                Log.d(TAG, "Front ID matched: " + Integer.parseInt(hexData[3], 16));

                                frontPressurePSI = psi;
                                // Set front tire status
                                if (psi <= lowPressure) {
                                    frontStatus = 1;
                                } else if (psi >= highPressure) {
                                    frontStatus = 2;
                                } else {
                                    frontStatus = 0;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtFrontTPMS = (TextView) findViewById(R.id.textViewFrontTPMS);
                                    txtFrontTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtFrontTPMS
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (frontStatus != 0) {
                                        txtFrontTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtFrontTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            } else if (Integer.parseInt(hexData[3], 16) > 2) {
                                Log.d(TAG, "Rear ID matched: " + Integer.parseInt(hexData[3], 16));

                                rearPressurePSI = psi;
                                // Set rear tire status
                                if (psi <= lowPressure) {
                                    rearStatus = 4;
                                } else if (psi >= highPressure) {
                                    rearStatus = 5;
                                } else {
                                    rearStatus = 3;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtRearTPMS = (TextView) findViewById(R.id.textViewRearTPMS);
                                    txtRearTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtRearTPMS.setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (rearStatus != 3) {
                                        txtRearTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtRearTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            }
                            // Reset icon
                            if ((frontStatus == 0) && (rearStatus == 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_on);
                            }
                            if ((frontStatus != 0) || (rearStatus != 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_alert);
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(2));
                                editor.commit();

                                updateLayout();

                                int delay = (Integer
                                        .parseInt(sharedPrefs.getString("prefAudioAlertDelay", "30")) * 1000);
                                String currStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                if (alertTimer == 0) {
                                    alertTimer = System.currentTimeMillis();
                                } else {
                                    long currentTime = System.currentTimeMillis();
                                    long duration = (currentTime - alertTimer);
                                    if (!currStatus.equals(lastStatus) || duration >= delay) {
                                        alertTimer = 0;
                                        if ((frontStatus == 1) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowFrontPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highFrontPressure));
                                        } else if ((rearStatus == 4) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowRearPressure));
                                        } else if ((rearStatus == 5) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontLowRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontHighRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontHighRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontLowRearPressure));
                                        }
                                        lastStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                    }
                                }
                            }
                        } catch (NumberFormatException e) {
                            Log.d(TAG, "Malformed message, unexpected value");
                        }
                        if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                            // Log data
                            if (logger == null) {
                                logger = new LogData();
                            }
                            if (logger != null) {
                                logger.write(String.valueOf(sbhex));
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    // Sensor Stuff
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    // Light
    if (lightSensor == null) {
        Log.d(TAG, "Light sensor not found");
    } else {
        sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        hasSensor = true;
    }
    // Compass
    sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
    sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);

    // Try to connect to CANBusGateway
    canBusConnect();
    // Connect to iTPMS if enabled
    if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        iTPMSConnect();
    }
}

From source file:nl.mpcjanssen.simpletask.Simpletask.java

private void updateRightDrawer() {
    ArrayList<String> names = new ArrayList<String>();
    final ArrayList<ActiveFilter> filters = getSavedFilter();
    Collections.sort(filters, new Comparator<ActiveFilter>() {
        public int compare(@NotNull ActiveFilter f1, @NotNull ActiveFilter f2) {
            return f1.getName().compareToIgnoreCase(f2.getName());
        }/*from ww w  .j a v a2s. c  om*/
    });
    for (ActiveFilter f : filters) {
        names.add(f.getName());
    }
    m_rightDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, names));
    m_rightDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
    m_rightDrawerList.setLongClickable(true);
    m_rightDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mFilter = filters.get(position);
            Intent intent = getIntent();
            mFilter.saveInIntent(intent);
            setIntent(intent);
            mFilter.saveInPrefs(TodoApplication.getPrefs());
            m_adapter.setFilteredTasks();
            if (m_drawerLayout != null) {
                m_drawerLayout.closeDrawer(Gravity.RIGHT);
            }
            finishActionmode();
            updateDrawers();
        }
    });
    m_rightDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            final ActiveFilter filter = filters.get(position);
            final String prefsName = filter.getPrefName();
            PopupMenu popupMenu = new PopupMenu(Simpletask.this, view);
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(@NotNull MenuItem item) {
                    int menuid = item.getItemId();
                    switch (menuid) {
                    case R.id.menu_saved_filter_delete:
                        deleteSavedFilter(prefsName);
                        break;
                    case R.id.menu_saved_filter_shortcut:
                        createFilterShortcut(filter);
                        break;
                    case R.id.menu_saved_filter_rename:
                        renameSavedFilter(prefsName);
                        break;
                    case R.id.menu_saved_filter_update:
                        updateSavedFilter(prefsName);
                        break;
                    default:
                        break;
                    }
                    return true;
                }
            });
            MenuInflater inflater = popupMenu.getMenuInflater();
            inflater.inflate(R.menu.saved_filter, popupMenu.getMenu());
            popupMenu.show();
            return true;
        }
    });
}