Example usage for android.content.res Resources getString

List of usage examples for android.content.res Resources getString

Introduction

In this page you can find the example usage for android.content.res Resources getString.

Prototype

@NonNull
public String getString(@StringRes int id) throws NotFoundException 

Source Link

Document

Return the string value associated with a particular resource ID.

Usage

From source file:com.aimfire.main.MainActivity.java

/**
 * share only to certain apps. code based on "http://stackoverflow.com/questions/
 * 9730243/how-to-filter-specific-apps-for-action-send-intent-and-set-a-different-
 * text-for/18980872#18980872"/*w w w  .ja v  a2 s .  c  o m*/
 *
 * "copy link" inspired by http://cketti.de/2016/06/15/share-url-to-clipboard/
 *
 * in general, "deep linking" is supported by the apps below. Facebook, Wechat,
 * Telegram are exceptions. click on the link would bring users to the landing
 * page.
 *
 * Facebook doesn't take our EXTRA_TEXT so user will have to "copy link" first
 * then paste the link
 */
private void inviteFriend() {
    mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_INVITE, null);

    Resources resources = getResources();

    /*
     * construct link
     */
    String appLink = resources.getString(R.string.app_store_link);

    /*
     * message subject and text
     */
    String emailSubject, emailText, twitterText;

    emailSubject = resources.getString(R.string.emailSubjectInviteFriend);
    emailText = resources.getString(R.string.emailBodyInviteFriend) + appLink;
    twitterText = resources.getString(R.string.emailBodyInviteFriend) + appLink + ", "
            + resources.getString(R.string.app_hashtag);

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
    //emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_native)));
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");

    Intent openInChooser = Intent.createChooser(emailIntent, resources.getString(R.string.share_chooser_text));

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if (packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if (packageName.contains("twitter") || packageName.contains("facebook")
                || packageName.contains("whatsapp") || packageName.contains("tencent.mm") || //wechat
                packageName.contains("line") || packageName.contains("skype") || packageName.contains("viber")
                || packageName.contains("kik") || packageName.contains("sgiggle") || //tango
                packageName.contains("kakao") || packageName.contains("telegram")
                || packageName.contains("nimbuzz") || packageName.contains("hike")
                || packageName.contains("imoim") || packageName.contains("bbm")
                || packageName.contains("threema") || packageName.contains("mms")
                || packageName.contains("android.apps.messaging") || //google messenger
                packageName.contains("android.talk") || //google hangouts
                packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if (packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, twitterText);
            } else if (packageName.contains("facebook")) {
                /*
                 * the warning below is wrong! at least on GS5, Facebook client does take
                 * our text, however it seems it takes only the first hyperlink in the
                 * text.
                 *
                 * Warning: Facebook IGNORES our text. They say "These fields are intended
                 * for users to express themselves. Pre-filling these fields erodes the
                 * authenticity of the user voice."
                 * One workaround is to use the Facebook SDK to post, but that doesn't
                 * allow the user to choose how they want to share. We can also make a
                 * custom landing page, and the link will show the <meta content ="...">
                 * text from that page with our link in Facebook.
                 */
                intent.putExtra(Intent.EXTRA_TEXT, appLink);
            } else if (packageName.contains("tencent.mm")) //wechat
            {
                /*
                 * wechat appears to do this similar to Facebook
                 */
                intent.putExtra(Intent.EXTRA_TEXT, appLink);
            } else if (packageName.contains("android.gm")) {
                // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
                //intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
                intent.setType("message/rfc822");
            } else if (packageName.contains("android.apps.docs")) {
                /*
                 * google drive - no reason to send link to it
                 */
                continue;
            } else {
                intent.putExtra(Intent.EXTRA_TEXT, emailText);
            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    /*
     *  create "Copy Link To Clipboard" Intent
     */
    Intent clipboardIntent = new Intent(this, CopyToClipboardActivity.class);
    clipboardIntent.setData(Uri.parse(appLink));
    intentList.add(new LabeledIntent(clipboardIntent, getPackageName(),
            getResources().getString(R.string.clipboard_activity_name), R.drawable.ic_copy_link));

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);
}

From source file:com.android.gallery3d.filtershow.imageshow.ImageShow.java

private void setupImageShow(Context context) {
    Resources res = context.getResources();
    mTextSize = res.getDimensionPixelSize(R.dimen.photoeditor_text_size);
    mTextPadding = res.getDimensionPixelSize(R.dimen.photoeditor_text_padding);
    mOriginalTextMargin = res.getDimensionPixelSize(R.dimen.photoeditor_original_text_margin);
    mOriginalTextSize = res.getDimensionPixelSize(R.dimen.photoeditor_original_text_size);
    mBackgroundColor = res.getColor(R.color.background_screen);
    mOriginalText = res.getString(R.string.original_picture_text);
    mShadow = (NinePatchDrawable) res.getDrawable(R.drawable.geometry_shadow);
    setupGestureDetector(context);/*from w  w w.  j  a va 2s. c  o  m*/
    mActivity = (FilterShowActivity) context;
    if (sMask == null) {
        Bitmap mask = BitmapFactory.decodeResource(res, R.drawable.spot_mask);
        sMask = convertToAlphaMask(mask);
    }
    mEdgeEffect = new EdgeEffectCompat(context);
    mEdgeSize = res.getDimensionPixelSize(R.dimen.edge_glow_size);
}

From source file:com.appeaser.sublimepickerlibrary.timepicker.SublimeTimePicker.java

private void initializeLayout() {
    mContext = getContext();//  w  ww . j a v  a  2 s .  c  om
    setCurrentLocale(Locale.getDefault());

    // process style attributes
    final TypedArray a = mContext.obtainStyledAttributes(R.styleable.SublimeTimePicker);
    final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final Resources res = mContext.getResources();

    mSelectHours = res.getString(R.string.select_hours);
    mSelectMinutes = res.getString(R.string.select_minutes);

    DateFormatSymbols dfs = DateFormatSymbols.getInstance(mCurrentLocale);
    String[] amPmStrings = dfs.getAmPmStrings();/*{"AM", "PM"}*/

    if (amPmStrings.length == 2 && !TextUtils.isEmpty(amPmStrings[0]) && !TextUtils.isEmpty(amPmStrings[1])) {
        mAmText = amPmStrings[0].length() > 2 ? amPmStrings[0].substring(0, 2) : amPmStrings[0];
        mPmText = amPmStrings[1].length() > 2 ? amPmStrings[1].substring(0, 2) : amPmStrings[1];
    } else {
        // Defaults
        mAmText = "AM";
        mPmText = "PM";
    }

    final int layoutResourceId = R.layout.time_picker_layout;
    final View mainView = inflater.inflate(layoutResourceId, this);

    mHeaderView = mainView.findViewById(R.id.time_header);

    // Set up hour/minute labels.
    mHourView = (TextView) mainView.findViewById(R.id.hours);
    mHourView.setOnClickListener(mClickListener);

    ViewCompat.setAccessibilityDelegate(mHourView, new ClickActionDelegate(mContext, R.string.select_hours));

    mSeparatorView = (TextView) mainView.findViewById(R.id.separator);

    mMinuteView = (TextView) mainView.findViewById(R.id.minutes);
    mMinuteView.setOnClickListener(mClickListener);

    ViewCompat.setAccessibilityDelegate(mMinuteView,
            new ClickActionDelegate(mContext, R.string.select_minutes));

    // Now that we have text appearances out of the way, make sure the hour
    // and minute views are correctly sized.
    mHourView.setMinWidth(computeStableWidth(mHourView, 24));
    mMinuteView.setMinWidth(computeStableWidth(mMinuteView, 60));

    // Set up AM/PM labels.
    mAmPmLayout = mainView.findViewById(R.id.ampm_layout);
    mAmLabel = (CheckedTextView) mAmPmLayout.findViewById(R.id.am_label);
    mAmLabel.setText(obtainVerbatim(amPmStrings[0]));
    mAmLabel.setOnClickListener(mClickListener);
    mPmLabel = (CheckedTextView) mAmPmLayout.findViewById(R.id.pm_label);
    mPmLabel.setText(obtainVerbatim(amPmStrings[1]));
    mPmLabel.setOnClickListener(mClickListener);

    ColorStateList headerTextColor = a.getColorStateList(R.styleable.SublimeTimePicker_spHeaderTextColor);

    if (headerTextColor != null) {
        mHourView.setTextColor(headerTextColor);
        mSeparatorView.setTextColor(headerTextColor);
        mMinuteView.setTextColor(headerTextColor);
        mAmLabel.setTextColor(headerTextColor);
        mPmLabel.setTextColor(headerTextColor);
    }

    // Set up header background, if available.
    if (SUtils.isApi_22_OrHigher()) {
        if (a.hasValueOrEmpty(R.styleable.SublimeTimePicker_spHeaderBackground)) {
            SUtils.setViewBackground(mHeaderView,
                    a.getDrawable(R.styleable.SublimeTimePicker_spHeaderBackground));
        }
    } else {
        if (a.hasValue(R.styleable.SublimeTimePicker_spHeaderBackground)) {
            SUtils.setViewBackground(mHeaderView,
                    a.getDrawable(R.styleable.SublimeTimePicker_spHeaderBackground));
        }
    }

    a.recycle();

    mRadialTimePickerView = (RadialTimePickerView) mainView.findViewById(R.id.radial_picker);

    setupListeners();

    mAllowAutoAdvance = true;

    // Set up for keyboard mode.
    mDoublePlaceholderText = res.getString(R.string.time_placeholder);
    mDeletedKeyFormat = res.getString(R.string.deleted_key);
    mPlaceholderText = mDoublePlaceholderText.charAt(0);
    mAmKeyCode = mPmKeyCode = -1;
    generateLegalTimesTree();

    // Initialize with current time
    final Calendar calendar = Calendar.getInstance(mCurrentLocale);
    final int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
    final int currentMinute = calendar.get(Calendar.MINUTE);
    initialize(currentHour, currentMinute, false /* 12h */, HOUR_INDEX);
}

From source file:com.ichi2.anki2.CardBrowser.java

@Override
protected Dialog onCreateDialog(int id) {
    StyledDialog dialog = null;//from   w w w.ja v  a 2s  .c om
    Resources res = getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(this);

    switch (id) {
    case DIALOG_ORDER:
        builder.setTitle(res.getString(R.string.card_browser_change_display_order_title));
        builder.setMessage(res.getString(R.string.card_browser_change_display_order_reverse));
        builder.setIcon(android.R.drawable.ic_menu_sort_by_size);
        builder.setSingleChoiceItems(res.getStringArray(R.array.card_browser_order_labels), mOrder,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        if (which != mOrder) {
                            mOrder = which;
                            mOrderAsc = false;
                            try {
                                if (mOrder == 0) {
                                    mCol.getConf().put("sortType", fSortTypes[1]);
                                    AnkiDroidApp.getSharedPrefs(getBaseContext()).edit()
                                            .putBoolean("cardBrowserNoSorting", true).commit();
                                } else {
                                    mCol.getConf().put("sortType", fSortTypes[mOrder]);
                                    AnkiDroidApp.getSharedPrefs(getBaseContext()).edit()
                                            .putBoolean("cardBrowserNoSorting", false).commit();
                                }
                                // default to descending for non-text fields
                                if (fSortTypes[mOrder].equals("noteFld")) {
                                    mOrderAsc = true;
                                }
                                mCol.getConf().put("sortBackwards", mOrderAsc);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                            searchCards();
                        } else if (which != CARD_ORDER_NONE) {
                            mOrderAsc = !mOrderAsc;
                            try {
                                mCol.getConf().put("sortBackwards", mOrderAsc);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                            Collections.reverse(mCards);
                            updateList();
                        }
                    }
                });
        dialog = builder.create();
        break;

    case DIALOG_CONTEXT_MENU:
        // FIXME:
        String[] entries = new String[4];
        @SuppressWarnings("unused")
        MenuItem item;
        entries[CONTEXT_MENU_MARK] = res.getString(R.string.card_browser_mark_card);
        entries[CONTEXT_MENU_SUSPEND] = res.getString(R.string.card_browser_suspend_card);
        entries[CONTEXT_MENU_DELETE] = res.getString(R.string.card_browser_delete_card);
        entries[CONTEXT_MENU_DETAILS] = res.getString(R.string.card_browser_card_details);
        builder.setTitle("contextmenu");
        builder.setIcon(R.drawable.ic_menu_manage);
        builder.setItems(entries, mContextMenuListener);
        dialog = builder.create();
        break;

    case DIALOG_TAGS:
        allTags = mCol.getTags().all();
        builder.setTitle(R.string.studyoptions_limit_select_tags);
        builder.setMultiChoiceItems(allTags, new boolean[allTags.length],
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String tag = allTags[which];
                        if (mSelectedTags.contains(tag)) {
                            Log.i(AnkiDroidApp.TAG, "unchecked tag: " + tag);
                            mSelectedTags.remove(tag);
                        } else {
                            Log.i(AnkiDroidApp.TAG, "checked tag: " + tag);
                            mSelectedTags.add(tag);
                        }
                    }
                });
        builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSearchEditText.setText("");
                String tags = mSelectedTags.toString();
                mSearchEditText.setHint(getResources().getString(R.string.card_browser_tags_shown,
                        tags.substring(1, tags.length() - 1)));
                StringBuilder sb = new StringBuilder();
                for (String tag : mSelectedTags) {
                    sb.append("tag:").append(tag).append(" ");
                }
                mSearchTerms = sb.toString();
                searchCards();
            }
        });
        builder.setNegativeButton(res.getString(R.string.cancel), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSelectedTags.clear();
            }
        });
        builder.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                mSelectedTags.clear();
            }
        });
        dialog = builder.create();
        break;
    // TODO(flerda@gmail.com): Fix card browser fields. See above.
    // https://code.google.com/p/ankidroid/issues/detail?id=1310
    /*
    case DIALOG_FIELD:
        builder.setTitle(res
                .getString(R.string.card_browser_field_title));
        builder.setIcon(android.R.drawable.ic_menu_sort_by_size);
            
        HashMap<String, String> card = mAllCards.get(0);
            
        String[][] items = mCol.getCard(Long.parseLong( card.get("id") )).note().items();
            
        mFields = new String[items.length+1];
        mFields[0]="SFLD";
            
        for (int i = 0; i < items.length; i++) {
            mFields[i+1] = items[i][0];
        }
            
        builder.setSingleChoiceItems(mFields, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int which) {
                if (which != mField) {
                    mField = which;
                    AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit()
                        .putInt("cardBrowserField", mField).commit();
                    getCards();
                }
            }
        });
        dialog = builder.create();
        break;
    */
    }
    return dialog;
}

From source file:com.hichinaschool.flashcards.anki.CardBrowser.java

@Override
protected Dialog onCreateDialog(int id) {
    StyledDialog dialog = null;//  w  w w  . ja  v  a  2 s. c  o  m
    Resources res = getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(this);

    switch (id) {
    case DIALOG_ORDER:
        builder.setTitle(res.getString(R.string.card_browser_change_display_order_title));
        builder.setMessage(res.getString(R.string.card_browser_change_display_order_reverse));
        builder.setIcon(android.R.drawable.ic_menu_sort_by_size);
        builder.setSingleChoiceItems(res.getStringArray(R.array.card_browser_order_labels), mOrder,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        if (which != mOrder) {
                            mOrder = which;
                            mOrderAsc = false;
                            try {
                                if (mOrder == 0) {
                                    mCol.getConf().put("sortType", fSortTypes[1]);
                                    AnkiDroidApp.getSharedPrefs(getBaseContext()).edit()
                                            .putBoolean("cardBrowserNoSorting", true).commit();
                                } else {
                                    mCol.getConf().put("sortType", fSortTypes[mOrder]);
                                    AnkiDroidApp.getSharedPrefs(getBaseContext()).edit()
                                            .putBoolean("cardBrowserNoSorting", false).commit();
                                }
                                // default to descending for non-text fields
                                if (fSortTypes[mOrder].equals("noteFld")) {
                                    mOrderAsc = true;
                                }
                                mCol.getConf().put("sortBackwards", mOrderAsc);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                            searchCards();
                        } else if (which != CARD_ORDER_NONE) {
                            mOrderAsc = !mOrderAsc;
                            try {
                                mCol.getConf().put("sortBackwards", mOrderAsc);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                            Collections.reverse(mCards);
                            updateList();
                        }
                    }
                });
        dialog = builder.create();
        break;

    case DIALOG_CONTEXT_MENU:
        // FIXME:
        String[] entries = new String[4];
        @SuppressWarnings("unused")
        MenuItem item;
        entries[CONTEXT_MENU_MARK] = res.getString(R.string.card_browser_mark_card);
        entries[CONTEXT_MENU_SUSPEND] = res.getString(R.string.card_browser_suspend_card);
        entries[CONTEXT_MENU_DELETE] = res.getString(R.string.card_browser_delete_card);
        entries[CONTEXT_MENU_DETAILS] = res.getString(R.string.card_browser_card_details);
        builder.setTitle("contextmenu");
        builder.setIcon(R.drawable.ic_menu_manage);
        builder.setItems(entries, mContextMenuListener);
        dialog = builder.create();
        break;

    case DIALOG_TAGS:
        allTags = mCol.getTags().all();
        builder.setTitle(R.string.studyoptions_limit_select_tags);
        builder.setMultiChoiceItems(allTags, new boolean[allTags.length],
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String tag = allTags[which];
                        if (mSelectedTags.contains(tag)) {
                            // Log.i(AnkiDroidApp.TAG, "unchecked tag: " + tag);
                            mSelectedTags.remove(tag);
                        } else {
                            // Log.i(AnkiDroidApp.TAG, "checked tag: " + tag);
                            mSelectedTags.add(tag);
                        }
                    }
                });
        builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSearchEditText.setText("");
                String tags = mSelectedTags.toString();
                mSearchEditText.setHint(getResources().getString(R.string.card_browser_tags_shown,
                        tags.substring(1, tags.length() - 1)));
                StringBuilder sb = new StringBuilder();
                for (String tag : mSelectedTags) {
                    sb.append("tag:").append(tag).append(" ");
                }
                mSearchTerms = sb.toString();
                searchCards();
            }
        });
        builder.setNegativeButton(res.getString(R.string.cancel), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mSelectedTags.clear();
            }
        });
        builder.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                mSelectedTags.clear();
            }
        });
        dialog = builder.create();
        break;
    // TODO(flerda@gmail.com): Fix card browser fields. See above.
    // https://code.google.com/p/ankidroid/issues/detail?id=1310
    /*
    case DIALOG_FIELD:
        builder.setTitle(res
                .getString(R.string.card_browser_field_title));
        builder.setIcon(android.R.drawable.ic_menu_sort_by_size);
            
        HashMap<String, String> card = mAllCards.get(0);
            
        String[][] items = mCol.getCard(Long.parseLong( card.get("id") )).note().items();
            
        mFields = new String[items.length+1];
        mFields[0]="SFLD";
            
        for (int i = 0; i < items.length; i++) {
            mFields[i+1] = items[i][0];
        }
            
        builder.setSingleChoiceItems(mFields, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int which) {
                if (which != mField) {
                    mField = which;
                    AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit()
                        .putInt("cardBrowserField", mField).commit();
                    getCards();
                }
            }
        });
        dialog = builder.create();
        break;
    */
    }
    return dialog;
}

From source file:at.flack.MailOutActivity.java

public void updateContactList(MainActivity activity) {
    ArrayList<Email> emails;
    try {//  w w  w  .j a va  2  s.  co  m
        emails = loadMails();
    } catch (IOException e1) {
        if (swipe != null)
            swipe.setRefreshing(false);
        if (progressbar != null)
            progressbar.setVisibility(View.INVISIBLE);
        return;
    }
    mailOutList = new ArrayList<ContactModel>();
    ContactModel model = null;
    Resources res = activity.getResources();
    for (Email mail : emails) {//
        model = new ContactModel(ProfilePictureCache.getInstance(activity).get(mail.getSender()),
                mail.getSubject(), mail.getText(), getDate(mail.getDate()), mail.isRead(), mail.getSender(),
                mail.getRecipient(), mail.getSenderName());
        if (KeySafe.getInstance(activity).contains(mail.getSender()) && Base64.isBase64(mail.getSubject())) {
            KeyEntity key = KeySafe.getInstance(activity).get(mail.getSender());
            if (key.getVersion() != KeyEntity.ECDH_PRIVATE_KEY) {
                model.setEncrypted(View.VISIBLE);
                try {
                    model.setTitle(new Message(mail.getSubject()).decryptedMessage(key));
                } catch (MessageDecrypterException e) {
                }
            }
        }
        // Pre Shared Exchange
        if ((mail.getText().toString().length() == 10 || mail.getText().toString().length() == 9)
                && mail.getText().toString().charAt(0) == '%') { // 4
            if (Base64.isPureBase64(mail.getText().toString().substring(1, 9))) {
                model.setTitle(res.getString(R.string.handshake_message));
            }
        }
        // DH Exchange
        if ((mail.getText()).toString().length() >= 120 && mail.getText().toString().length() < 125
                && mail.getText().toString().charAt(0) == '%') { // DH
            // Exchange!
            if (Base64.isPureBase64(
                    mail.getText().toString().substring(1, mail.getText().toString().lastIndexOf("=")))) {
                model.setTitle(res.getString(R.string.handshake_message));
            }
        }
        mailOutList.add(model);
    }

    if (contactList != null && contactList.getAdapter() == null) {
        ContactAdapter arrayAdapter = new ContactAdapter(activity, mailOutList, 0);
        arrayAdapter.notifyDataSetChanged();
        contactList.setAdapter(arrayAdapter);
        contactList.setSelection(0);
    } else if (mailOutList.size() > 0 && contactList != null) {
        ((ContactAdapter) ((HeaderViewListAdapter) contactList.getAdapter()).getWrappedAdapter())
                .refill(mailOutList, 0);
    }
    if (swipe != null)
        swipe.setRefreshing(false);
    if (progressbar != null)
        progressbar.setVisibility(View.INVISIBLE);
    if (loadmore != null)
        loadmore.setEnabled(true);
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

public void StateChanged(MessageProcessorStates oldState, MessageProcessorStates newState) {
    switch (newState) {
    case NotConnected:
        // Add this line if we should try and reconnect if we are not
        // connected
        // _iBACservice.Reset();

        _handler.obtainMessage(IBAC.ADD_BOTTOM_MESSAGE, getResources().getString(R.string.channel_closed))
                .sendToTarget();//from  ww  w  .j a  v a  2s.c  o  m
        ShutdownAction action = new ShutdownAction(_handler, 5, Session.isFullyExit);
        action.Invoke(null);
        break;
    case Connected:
        _handler.obtainMessage(IBAC.ADD_MESSAGE, getResources().getString(R.string.please_wait)).sendToTarget();
        break;
    case WaitingForResponse:
        // _handler.obtainMessage(IBAC.ADD_MESSAGE,
        // "Please wait...").sendToTarget();
        break;
    case Ready:
        _handler.obtainMessage(IBAC.MESSAGE_TAKE_PHOTO, getResources().getString(R.string.blow_into_device))
                .sendToTarget();
        // _handler.obtainMessage(IBAC.ADD_MESSAGE, "Ready").sendToTarget();
        break;
    case TestInProgress:
        //
        // countdownHandler.postDelayed(countdownRunnable, 0);
        break;
    case TestReceived:

        com.kjsaw.alcosys.ibacapp.MessageUtils.Message resultMessage = _iBACservice._messageProcessor
                .GetMessageSequence().GetLastMessage();
        if (resultMessage == null) {
            _handler.obtainMessage(IBAC.ADD_MESSAGE, getResources().getString(R.string.result_bad))
                    .sendToTarget();

            ShutdownAction shutDownAction = new ShutdownAction(_handler, 5, true);
            shutDownAction.Invoke(null);
            return;
        }

        float value = calibrateResult(SuccessRule.ParseValue(resultMessage));
        // Foks Comments
        // float value = calibrateResult(0.07f);

        String asString = StringHelper.PadString("" + value, 5, '0', false);

        if (value >= 0) {
            // countdownHandler.postDelayed(countdownRunnable, 0);
            capturePhoto();
            _handler.obtainMessage(IBAC.ADD_SUCCESS_MESSAGE,
                    getResources().getString(R.string.result_measured_to) + " " + asString + " "
                            + getResources().getString(R.string.alco_level_acronym))
                    .sendToTarget();
            _iBACservice.endOperation();
            boolean isWait = true;
            while (isWait) {
                showImageEndTime = System.currentTimeMillis();
                if (bitmapPhoto != null && (Session.IBAC_VERSION != null && !Session.IBAC_VERSION.equals(""))
                        && (Session.PHONE_NUMBER != null && !Session.PHONE_NUMBER.equals(""))
                        && ((showImageTime - (showImageEndTime - showImageStartTime) / 1000) < 0)
                        && deviceLocation.isGPSStoped()) {
                    Log.i("SAM", "Waiting while registering result ...");
                    positionLatitude = deviceLocation.getLatitude();
                    positionLongitude = deviceLocation.getLongitude();
                    positionAccuracy = deviceLocation.getAccuracy();
                    isWait = false;
                }
            }
            Log.i("SAM", "Sending result to server...");
            //boolean sendResult = sendResultToServer(value);
            boolean sendResult = true;

            if (sendResult) {
                Resources resources = getResources();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(resources.getString(R.string.result_success_title));
                stringBuffer.append("\n");
                stringBuffer.append(resources.getString(R.string.result_success_value) + " " + value + " "
                        + resources.getString(R.string.result_success_unit));
                stringBuffer.append("\n");
                stringBuffer.append(resources.getString(R.string.result_success_time_format_start)
                        + Session.REQUEST_DATE + resources.getString(R.string.result_success_time_format_end));
                stringBuffer.append("\n");
                stringBuffer.append(resources.getString(R.string.result_success_sent));

                _handler.obtainMessage(IBAC.ADD_SENT_MESSAGE, stringBuffer.toString()).sendToTarget();
            } else {
                _handler.obtainMessage(IBAC.ADD_SENT_MESSAGE,
                        getResources().getString(R.string.result_com_failure)).sendToTarget();
            }

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            // bad result
            _handler.obtainMessage(IBAC.ADD_MESSAGE, getResources().getString(R.string.result_bad))
                    .sendToTarget();
        }

        _iBACservice._messageProcessor.messageCompleted();
        // ShutdownAction shutDownForReceived = new ShutdownAction(_handler, 5, false);
        // shutDownForReceived.Invoke(null);

        break;
    case Completed:
        Resources resources = getResources();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(resources.getString(R.string.result_completed_content1));
        stringBuffer.append("\n");
        stringBuffer.append(resources.getString(R.string.result_completed_content2));
        stringBuffer.append("\n");
        stringBuffer.append(resources.getString(R.string.result_completed_content3));
        _handler.obtainMessage(IBAC.COMPLETE_SENT_MESSAGE, stringBuffer.toString()).sendToTarget();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ShutdownAction shutDownForReceived = new ShutdownAction(_handler, 5, false);
        shutDownForReceived.Invoke(null);
        break;
    case Error:
        String errorMessage = _iBACservice._messageProcessor.GetLastUserMessage()
                .GetDescription(getResources());
        if (errorMessage == null || errorMessage == "") {
            _handler.obtainMessage(IBAC.ADD_MESSAGE, getResources().getString(R.string.unknown_error))
                    .sendToTarget();
        } else {
            _handler.obtainMessage(IBAC.ADD_MESSAGE, errorMessage).sendToTarget();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        break;
    default:
        break;
    }
}

From source file:com.hichinaschool.flashcards.anki.CardEditor.java

private StyledDialog createDialogIntentInformation(Builder builder, Resources res) {
    builder.setTitle(res.getString(R.string.intent_add_saved_information));
    ListView listView = new ListView(this);

    mIntentInformationAdapter = new SimpleAdapter(this, mIntentInformation, R.layout.card_item,
            new String[] { "source", "target", "id" },
            new int[] { R.id.card_sfld, R.id.card_tmpl, R.id.card_item });
    listView.setAdapter(mIntentInformationAdapter);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override/*from  w w w.  j  a v a 2  s .c om*/
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(CardEditor.this, CardEditor.class);
            intent.putExtra(EXTRA_CALLER, CALLER_CARDEDITOR_INTENT_ADD);
            HashMap<String, String> map = mIntentInformation.get(position);
            intent.putExtra(EXTRA_CONTENTS, map.get("fields"));
            intent.putExtra(EXTRA_ID, map.get("id"));
            startActivityForResult(intent, REQUEST_INTENT_ADD);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(CardEditor.this, ActivityTransitionAnimation.FADE);
            }
            mIntentInformationDialog.dismiss();
        }
    });
    mCardItemBackground = Themes.getCardBrowserBackground()[0];
    mIntentInformationAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object arg1, String text) {
            if (view.getId() == R.id.card_item) {
                view.setBackgroundResource(mCardItemBackground);
                return true;
            }
            return false;
        }
    });
    listView.setBackgroundColor(android.R.attr.colorBackground);
    listView.setDrawSelectorOnTop(true);
    listView.setFastScrollEnabled(true);
    Themes.setContentStyle(listView, Themes.CALLER_CARDEDITOR_INTENTDIALOG);
    builder.setView(listView, false, true);
    builder.setCancelable(true);
    builder.setPositiveButton(res.getString(R.string.intent_add_clear_all), new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int arg1) {
            MetaDB.resetIntentInformation(CardEditor.this);
            mIntentInformation.clear();
            dialog.dismiss();
        }
    });
    StyledDialog dialog = builder.create();
    mIntentInformationDialog = dialog;
    return dialog;
}

From source file:com.android.calendar.AllInOneActivity.java

@Override
protected void onCreate(Bundle icicle) {
    if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) {
        setTheme(R.style.CalendarTheme_WithActionBarWallpaper);
    }/*w w  w  .  j ava2  s. c om*/
    super.onCreate(icicle);
    dynamicTheme.onCreate(this);

    if (icicle != null && icicle.containsKey(BUNDLE_KEY_CHECK_ACCOUNTS)) {
        mCheckForAccounts = icicle.getBoolean(BUNDLE_KEY_CHECK_ACCOUNTS);
    }
    // Launch add google account if this is first time and there are no
    // accounts yet
    if (mCheckForAccounts && !Utils.getSharedPreference(this, GeneralPreferences.KEY_SKIP_SETUP, false)) {

        mHandler = new QueryHandler(this.getContentResolver());
        mHandler.startQuery(0, null, Calendars.CONTENT_URI, new String[] { Calendars._ID }, null,
                null /* selection args */, null /* sort order */);
    }

    // This needs to be created before setContentView
    mController = CalendarController.getInstance(this);

    // Check and ask for most needed permissions
    checkAppPermissions();

    // Get time from intent or icicle
    long timeMillis = -1;
    int viewType = -1;
    final Intent intent = getIntent();
    if (icicle != null) {
        timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
        viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1);
    } else {
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            // Open EventInfo later
            timeMillis = parseViewAction(intent);
        }

        if (timeMillis == -1) {
            timeMillis = Utils.timeFromIntentInMillis(intent);
        }
    }

    if (viewType == -1 || viewType > ViewType.MAX_VALUE) {
        viewType = Utils.getViewTypeFromIntentAndSharedPref(this);
    }
    mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
    Time t = new Time(mTimeZone);
    t.set(timeMillis);

    if (DEBUG) {
        if (icicle != null && intent != null) {
            Log.d(TAG, "both, icicle:" + icicle.toString() + "  intent:" + intent.toString());
        } else {
            Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent);
        }
    }

    Resources res = getResources();
    mHideString = res.getString(R.string.hide_controls);
    mShowString = res.getString(R.string.show_controls);
    mOrientation = res.getConfiguration().orientation;
    if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        mControlsAnimateWidth = (int) res.getDimension(R.dimen.calendar_controls_width);
        if (mControlsParams == null) {
            mControlsParams = new LayoutParams(mControlsAnimateWidth, 0);
        }
        mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    } else {
        // Make sure width is in between allowed min and max width values
        mControlsAnimateWidth = Math.max(res.getDisplayMetrics().widthPixels * 45 / 100,
                (int) res.getDimension(R.dimen.min_portrait_calendar_controls_width));
        mControlsAnimateWidth = Math.min(mControlsAnimateWidth,
                (int) res.getDimension(R.dimen.max_portrait_calendar_controls_width));
    }

    mControlsAnimateHeight = (int) res.getDimension(R.dimen.calendar_controls_height);

    mHideControls = !Utils.getSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, true);
    mIsMultipane = Utils.getConfigBool(this, R.bool.multiple_pane_config);
    mIsTabletConfig = Utils.getConfigBool(this, R.bool.tablet_config);
    mShowAgendaWithMonth = Utils.getConfigBool(this, R.bool.show_agenda_with_month);
    mShowCalendarControls = Utils.getConfigBool(this, R.bool.show_calendar_controls);
    mShowEventDetailsWithAgenda = Utils.getConfigBool(this, R.bool.show_event_details_with_agenda);
    mShowEventInfoFullScreenAgenda = Utils.getConfigBool(this, R.bool.agenda_show_event_info_full_screen);
    mShowEventInfoFullScreen = Utils.getConfigBool(this, R.bool.show_event_info_full_screen);
    mCalendarControlsAnimationTime = res.getInteger(R.integer.calendar_controls_animation_time);
    Utils.setAllowWeekForDetailView(mIsMultipane);

    // setContentView must be called before configureActionBar
    setContentView(R.layout.all_in_one_material);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

    mFab = (FloatingActionButton) findViewById(R.id.floating_action_button);

    if (mIsTabletConfig) {
        mDateRange = (TextView) findViewById(R.id.date_bar);
        mWeekTextView = (TextView) findViewById(R.id.week_num);
    } else {
        mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null);
    }

    setupToolbar(viewType);
    setupNavDrawer();
    setupFloatingActionButton();

    mHomeTime = (TextView) findViewById(R.id.home_time);
    mMiniMonth = findViewById(R.id.mini_month);
    if (mIsTabletConfig && mOrientation == Configuration.ORIENTATION_PORTRAIT) {
        mMiniMonth.setLayoutParams(
                new RelativeLayout.LayoutParams(mControlsAnimateWidth, mControlsAnimateHeight));
    }
    mCalendarsList = findViewById(R.id.calendar_list);
    mMiniMonthContainer = findViewById(R.id.mini_month_container);
    mSecondaryPane = findViewById(R.id.secondary_pane);

    // Must register as the first activity because this activity can modify
    // the list of event handlers in it's handle method. This affects who
    // the rest of the handlers the controller dispatches to are.
    mController.registerFirstEventHandler(HANDLER_KEY, this);

    initFragments(timeMillis, viewType, icicle);

    // Listen for changes that would require this to be refreshed
    SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    mContentResolver = getContentResolver();
}

From source file:com.borax12.materialdaterangepicker.time.TimePickerDialog.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    View view = inflater.inflate(R.layout.range_time_picker_dialog, null);
    KeyboardListener keyboardListener = new KeyboardListener();
    view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener);

    Resources res = getResources();
    mHourPickerDescription = res.getString(R.string.mdtp_hour_picker_description);
    mSelectHours = res.getString(R.string.mdtp_select_hours);
    mMinutePickerDescription = res.getString(R.string.mdtp_minute_picker_description);
    mSelectMinutes = res.getString(R.string.mdtp_select_minutes);
    mSelectedColor = res.getColor(R.color.mdtp_white);
    mUnselectedColor = res.getColor(R.color.mdtp_accent_color_focused);

    tabHost = (TabHost) view.findViewById(R.id.tabHost);
    tabHost.findViewById(R.id.tabHost);//from   w w w. java 2 s  . c  o m
    tabHost.setup();
    TabHost.TabSpec startDatePage = tabHost.newTabSpec("start");
    startDatePage.setContent(R.id.start_date_group);
    startDatePage.setIndicator("FROM");

    TabHost.TabSpec endDatePage = tabHost.newTabSpec("end");
    endDatePage.setContent(R.id.end_date_group);
    endDatePage.setIndicator("TO");

    tabHost.addTab(startDatePage);
    tabHost.addTab(endDatePage);

    mHourView = (TextView) view.findViewById(R.id.hours);
    mHourView.setOnKeyListener(keyboardListener);
    mHourViewEnd = (TextView) view.findViewById(R.id.hours_end);
    mHourViewEnd.setOnKeyListener(keyboardListener);
    mHourSpaceView = (TextView) view.findViewById(R.id.hour_space);
    mHourSpaceViewEnd = (TextView) view.findViewById(R.id.hour_space_end);
    mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space);
    mMinuteSpaceViewEnd = (TextView) view.findViewById(R.id.minutes_space_end);
    mMinuteView = (TextView) view.findViewById(R.id.minutes);
    mMinuteView.setOnKeyListener(keyboardListener);
    mMinuteViewEnd = (TextView) view.findViewById(R.id.minutes_end);
    mMinuteViewEnd.setOnKeyListener(keyboardListener);
    mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label);
    mAmPmTextView.setOnKeyListener(keyboardListener);
    mAmPmTextViewEnd = (TextView) view.findViewById(R.id.ampm_label_end);
    mAmPmTextViewEnd.setOnKeyListener(keyboardListener);
    String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
    mAmText = amPmTexts[0];
    mPmText = amPmTexts[1];

    mHapticFeedbackController = new HapticFeedbackController(getActivity());

    mTimePicker = (RadialPickerLayout) view.findViewById(R.id.time_picker);
    mTimePicker.setOnValueSelectedListener(this);
    mTimePicker.setOnKeyListener(keyboardListener);
    mTimePicker.initialize(getActivity(), this, mInitialHourOfDay, mInitialMinute, mIs24HourMode);

    mTimePickerEnd = (RadialPickerLayout) view.findViewById(R.id.time_picker_end);
    mTimePickerEnd.setOnValueSelectedListener(this);
    mTimePickerEnd.setOnKeyListener(keyboardListener);
    mTimePickerEnd.initialize(getActivity(), this, mInitialHourOfDay, mInitialMinute, mIs24HourMode);

    int currentItemShowing = HOUR_INDEX;
    int currentItemShowingEnd = HOUR_INDEX;
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) {
        currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING);
    }
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING_END)) {
        currentItemShowingEnd = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING_END);
    }
    setCurrentItemShowing(currentItemShowing, false, true, true);
    setCurrentItemShowing(currentItemShowingEnd, false, true, true);
    mTimePicker.invalidate();
    mTimePickerEnd.invalidate();

    mHourView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setCurrentItemShowing(HOUR_INDEX, true, false, true);
            tryVibrate();
        }
    });
    mHourViewEnd.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setCurrentItemShowing(HOUR_INDEX, true, false, true);
            tryVibrate();
        }
    });
    mMinuteView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setCurrentItemShowing(MINUTE_INDEX, true, false, true);
            tryVibrate();
        }
    });
    mMinuteViewEnd.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setCurrentItemShowing(MINUTE_INDEX, true, false, true);
            tryVibrate();
        }
    });

    mOkButton = (Button) view.findViewById(R.id.ok);
    mOkButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInKbMode && isTypedTimeFullyLegal()) {
                finishKbMode(false);
            } else {
                tryVibrate();
            }
            if (mCallback != null) {
                mCallback.onTimeSet(mTimePicker, mTimePicker.getHours(), mTimePicker.getMinutes(),
                        mTimePickerEnd.getHours(), mTimePickerEnd.getMinutes());
            }
            dismiss();
        }
    });
    mOkButton.setOnKeyListener(keyboardListener);
    mOkButton.setTypeface(TypefaceHelper.get(getDialog().getContext(), "Roboto-Medium"));

    mCancelButton = (Button) view.findViewById(R.id.cancel);
    mCancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tryVibrate();
            if (getDialog() != null)
                getDialog().cancel();
        }
    });
    mCancelButton.setTypeface(TypefaceHelper.get(getDialog().getContext(), "Roboto-Medium"));
    mCancelButton.setVisibility(isCancelable() ? View.VISIBLE : View.GONE);

    // Enable or disable the AM/PM view.
    mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
    mAmPmHitspaceEnd = view.findViewById(R.id.ampm_hitspace_end);

    if (mIs24HourMode) {
        mAmPmTextView.setVisibility(View.GONE);
        mAmPmTextViewEnd.setVisibility(View.GONE);

        RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
        TextView separatorView = (TextView) view.findViewById(R.id.separator);
        TextView separatorViewEnd = (TextView) view.findViewById(R.id.separator_end);
        separatorView.setLayoutParams(paramsSeparator);
        separatorViewEnd.setLayoutParams(paramsSeparator);
    } else {
        mAmPmTextView.setVisibility(View.VISIBLE);
        mAmPmTextViewEnd.setVisibility(View.VISIBLE);
        updateAmPmDisplay(mInitialHourOfDay < 12 ? AM : PM);
        mAmPmHitspace.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                tryVibrate();
                int amOrPm = mTimePicker.getIsCurrentlyAmOrPm();
                if (amOrPm == AM) {
                    amOrPm = PM;
                } else if (amOrPm == PM) {
                    amOrPm = AM;
                }
                updateAmPmDisplay(amOrPm);
                mTimePicker.setAmOrPm(amOrPm);
            }
        });
        mAmPmHitspaceEnd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                tryVibrate();
                int amOrPm = mTimePickerEnd.getIsCurrentlyAmOrPm();
                if (amOrPm == AM) {
                    amOrPm = PM;
                } else if (amOrPm == PM) {
                    amOrPm = AM;
                }
                updateAmPmDisplay(amOrPm);
                mTimePickerEnd.setAmOrPm(amOrPm);
            }
        });
    }

    mAllowAutoAdvance = true;
    setHour(mInitialHourOfDay, true);
    setMinute(mInitialMinute);

    // Set up for keyboard mode.
    mDoublePlaceholderText = res.getString(R.string.mdtp_time_placeholder);
    mDeletedKeyFormat = res.getString(R.string.mdtp_deleted_key);
    mPlaceholderText = mDoublePlaceholderText.charAt(0);
    mAmKeyCode = mPmKeyCode = -1;
    generateLegalTimesTree();
    if (mInKbMode) {
        mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES);
        tryStartingKbMode(-1);
        mHourView.invalidate();
        mHourViewEnd.invalidate();
    } else if (mTypedTimes == null) {
        mTypedTimes = new ArrayList<>();
    }

    // Set the title (if any)
    TextView timePickerHeader = (TextView) view.findViewById(R.id.time_picker_header);
    TextView timePickerHeaderEnd = (TextView) view.findViewById(R.id.time_picker_header_end);
    if (!mTitle.isEmpty()) {
        timePickerHeader.setVisibility(TextView.VISIBLE);
        timePickerHeader.setText(mTitle);
        timePickerHeaderEnd.setVisibility(TextView.VISIBLE);
        timePickerHeaderEnd.setText(mTitle);
    }

    // Set the theme at the end so that the initialize()s above don't counteract the theme.
    mTimePicker.setTheme(getActivity().getApplicationContext(), mThemeDark);
    mTimePickerEnd.setTheme(getActivity().getApplicationContext(), mThemeDark);

    //If an accent color has not been set manually, try and get it from the context
    if (mAccentColor == -1) {
        int accentColor = Utils.getAccentColorFromThemeIfAvailable(getActivity());
        if (accentColor != -1) {
            mAccentColor = accentColor;
        }
    }
    if (mAccentColor != -1) {
        mTimePicker.setAccentColor(mAccentColor);
        mTimePickerEnd.setAccentColor(mAccentColor);
        mOkButton.setTextColor(mAccentColor);
    } else {
        int circleBackground = res.getColor(R.color.mdtp_circle_background);
        int backgroundColor = res.getColor(R.color.mdtp_background_color);
        int darkBackgroundColor = res.getColor(R.color.mdtp_light_gray);
        int lightGray = res.getColor(R.color.mdtp_light_gray);

        mTimePicker.setBackgroundColor(mThemeDark ? lightGray : circleBackground);
        mTimePickerEnd.setBackgroundColor(mThemeDark ? lightGray : circleBackground);
        view.findViewById(R.id.time_picker_dialog)
                .setBackgroundColor(mThemeDark ? darkBackgroundColor : backgroundColor);
    }

    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            if (tabId == "start") {
                setCurrentItemShowing(mTimePicker.getCurrentItemShowing(), true, false, true);
                setHour(mTimePicker.getHours(), false);
                setMinute(mTimePicker.getMinutes());
                updateAmPmDisplay(mTimePicker.getIsCurrentlyAmOrPm());
            } else {
                setCurrentItemShowing(mTimePickerEnd.getCurrentItemShowing(), true, false, true);
                setHour(mTimePickerEnd.getHours(), false);
                setMinute(mTimePickerEnd.getMinutes());
                updateAmPmDisplay(mTimePickerEnd.getIsCurrentlyAmOrPm());
            }
        }
    });
    return view;
}