Example usage for android.webkit WebView getSettings

List of usage examples for android.webkit WebView getSettings

Introduction

In this page you can find the example usage for android.webkit WebView getSettings.

Prototype

public WebSettings getSettings() 

Source Link

Document

Gets the WebSettings object used to control the settings for this WebView.

Usage

From source file:com.ichi2.anki.AbstractFlashcardViewer.java

@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
// because of setDisplayZoomControls.
private WebView createWebView() {
    WebView webView = new MyWebView(this);
    webView.setWillNotCacheDrawing(true);
    webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    if (CompatHelper.isHoneycomb()) {
        // Disable the on-screen zoom buttons for API > 11
        webView.getSettings().setDisplayZoomControls(false);
    }//from w ww. j a  va 2s .c o m
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setSupportZoom(true);
    // Start at the most zoomed-out level
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new AnkiDroidWebChromeClient());
    // Problems with focus and input tags is the reason we keep the old type answer mechanism for old Androids.
    webView.setFocusableInTouchMode(mUseInputTag);
    webView.setScrollbarFadingEnabled(true);
    Timber.d("Focusable = %s, Focusable in touch mode = %s", webView.isFocusable(),
            webView.isFocusableInTouchMode());

    webView.setWebViewClient(new WebViewClient() {
        // Filter any links using the custom "playsound" protocol defined in Sound.java.
        // We play sounds through these links when a user taps the sound icon.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("playsound:")) {
                // Send a message that will be handled on the UI thread.
                Message msg = Message.obtain();
                String soundPath = url.replaceFirst("playsound:", "");
                msg.obj = soundPath;
                mHandler.sendMessage(msg);
                return true;
            }
            if (url.startsWith("file") || url.startsWith("data:")) {
                return false; // Let the webview load files, i.e. local images.
            }
            if (url.startsWith("typeblurtext:")) {
                // Store the text the javascript has send us
                mTypeInput = URLDecoder.decode(url.replaceFirst("typeblurtext:", ""));
                //  and show the SHOW ANSWER? button again.
                mFlipCardLayout.setVisibility(View.VISIBLE);
                return true;
            }
            if (url.startsWith("typeentertext:")) {
                // Store the text the javascript has send us
                mTypeInput = URLDecoder.decode(url.replaceFirst("typeentertext:", ""));
                //  and show the answer.
                mFlipCardLayout.performClick();
                return true;
            }
            if (url.equals("signal:typefocus")) {
                // Hide the SHOW ANSWER? button when the input has focus. The soft keyboard takes up enough space
                // by itself.
                mFlipCardLayout.setVisibility(View.GONE);
                return true;
            }
            Timber.d("Opening external link \"%s\" with an Intent", url);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            try {
                startActivityWithoutAnimation(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace(); // Don't crash if the intent is not handled
            }
            return true;
        }

        // Run any post-load events in javascript that rely on the window being completely loaded.
        @Override
        public void onPageFinished(WebView view, String url) {
            Timber.d("onPageFinished triggered");
            view.loadUrl("javascript:onPageFinished();");
        }
    });
    // Set transparent color to prevent flashing white when night mode enabled
    webView.setBackgroundColor(Color.argb(1, 0, 0, 0));
    return webView;
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@ReactProp(name = "source")
public void setSource(WebView view, @Nullable ReadableMap source) {
    if (source != null) {
        if (source.hasKey("html")) {
            String html = source.getString("html");
            if (source.hasKey("baseUrl")) {
                view.loadDataWithBaseURL(source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING,
                        null);/*  w  w  w.j a va2  s .c  o m*/
            } else {
                view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING);
            }
            return;
        }
        if (source.hasKey("uri")) {
            String url = source.getString("uri");
            String previousUrl = view.getUrl();
            if (previousUrl != null && previousUrl.equals(url)) {
                return;
            }
            if (source.hasKey("method")) {
                String method = source.getString("method");
                if (method.equals(HTTP_METHOD_POST)) {
                    byte[] postData = null;
                    if (source.hasKey("body")) {
                        String body = source.getString("body");
                        try {
                            postData = body.getBytes("UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            postData = body.getBytes();
                        }
                    }
                    if (postData == null) {
                        postData = new byte[0];
                    }
                    view.postUrl(url, postData);
                    return;
                }
            }
            HashMap<String, String> headerMap = new HashMap<>();
            if (source.hasKey("headers")) {
                ReadableMap headers = source.getMap("headers");
                ReadableMapKeySetIterator iter = headers.keySetIterator();
                while (iter.hasNextKey()) {
                    String key = iter.nextKey();
                    if ("user-agent".equals(key.toLowerCase(Locale.ENGLISH))) {
                        if (view.getSettings() != null) {
                            view.getSettings().setUserAgentString(headers.getString(key));
                        }
                    } else {
                        headerMap.put(key, headers.getString(key));
                    }
                }
            }
            view.loadUrl(url, headerMap);
            return;
        }
    }
    view.loadUrl(BLANK_URL);
}

From source file:com.mobicage.rogerthat.plugins.messaging.ServiceMessageDetailActivity.java

protected void updateMessageDetail(final boolean isUpdate) {
    T.UI();//w w  w  .  ja v a 2s. co m
    // Set sender avatar
    ImageView avatarImage = (ImageView) findViewById(R.id.avatar);
    String sender = mCurrentMessage.sender;
    setAvatar(avatarImage, sender);
    // Set sender name
    TextView senderView = (TextView) findViewById(R.id.sender);
    final String senderName = mFriendsPlugin.getName(sender);
    senderView.setText(senderName == null ? sender : senderName);
    // Set timestamp
    TextView timestampView = (TextView) findViewById(R.id.timestamp);
    timestampView.setText(TimeUtils.getDayTimeStr(this, mCurrentMessage.timestamp * 1000));

    // Set clickable region on top to go to friends detail
    final RelativeLayout messageHeader = (RelativeLayout) findViewById(R.id.message_header);
    messageHeader.setOnClickListener(getFriendDetailOnClickListener(mCurrentMessage.sender));
    messageHeader.setVisibility(View.VISIBLE);

    // Set message
    TextView messageView = (TextView) findViewById(R.id.message);
    WebView web = (WebView) findViewById(R.id.webview);
    FrameLayout flay = (FrameLayout) findViewById(R.id.message_details);
    Resources resources = getResources();
    flay.setBackgroundColor(resources.getColor(R.color.mc_background));
    boolean showBranded = false;

    int darkSchemeTextColor = resources.getColor(android.R.color.primary_text_dark);
    int lightSchemeTextColor = resources.getColor(android.R.color.primary_text_light);

    senderView.setTextColor(lightSchemeTextColor);
    timestampView.setTextColor(lightSchemeTextColor);

    BrandingResult br = null;
    if (!TextUtils.isEmptyOrWhitespace(mCurrentMessage.branding)) {
        boolean brandingAvailable = false;
        try {
            brandingAvailable = mMessagingPlugin.getBrandingMgr().isBrandingAvailable(mCurrentMessage.branding);
        } catch (BrandingFailureException e1) {
            L.d(e1);
        }
        try {
            if (brandingAvailable) {
                br = mMessagingPlugin.getBrandingMgr().prepareBranding(mCurrentMessage);
                WebSettings settings = web.getSettings();
                settings.setJavaScriptEnabled(false);
                settings.setBlockNetworkImage(false);
                web.loadUrl("file://" + br.file.getAbsolutePath());
                web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
                if (br.color != null) {
                    flay.setBackgroundColor(br.color);
                }
                if (!br.showHeader) {
                    messageHeader.setVisibility(View.GONE);
                    MarginLayoutParams mlp = (MarginLayoutParams) web.getLayoutParams();
                    mlp.setMargins(0, 0, 0, mlp.bottomMargin);
                } else if (br.scheme == ColorScheme.dark) {
                    senderView.setTextColor(darkSchemeTextColor);
                    timestampView.setTextColor(darkSchemeTextColor);
                }

                showBranded = true;
            } else {
                mMessagingPlugin.getBrandingMgr().queueGenericBranding(mCurrentMessage.branding);
            }
        } catch (BrandingFailureException e) {
            L.bug("Could not display message with branding: branding is available, but prepareBranding failed",
                    e);
        }
    }

    if (showBranded) {
        web.setVisibility(View.VISIBLE);
        messageView.setVisibility(View.GONE);
    } else {
        web.setVisibility(View.GONE);
        messageView.setVisibility(View.VISIBLE);
        messageView.setText(mCurrentMessage.message);
    }

    // Add list of members who did not ack yet
    FlowLayout memberSummary = (FlowLayout) findViewById(R.id.member_summary);
    memberSummary.removeAllViews();
    SortedSet<MemberStatusTO> memberSummarySet = new TreeSet<MemberStatusTO>(getMemberstatusComparator());
    for (MemberStatusTO ms : mCurrentMessage.members) {
        if ((ms.status & MessagingPlugin.STATUS_ACKED) != MessagingPlugin.STATUS_ACKED
                && !ms.member.equals(mCurrentMessage.sender)) {
            memberSummarySet.add(ms);
        }
    }
    FlowLayout.LayoutParams flowLP = new FlowLayout.LayoutParams(2, 0);
    for (MemberStatusTO ms : memberSummarySet) {
        FrameLayout fl = new FrameLayout(this);
        fl.setLayoutParams(flowLP);
        memberSummary.addView(fl);
        fl.addView(createParticipantView(ms));
    }
    memberSummary.setVisibility(memberSummarySet.size() < 2 ? View.GONE : View.VISIBLE);

    // Add members statuses
    final LinearLayout members = (LinearLayout) findViewById(R.id.members);
    members.removeAllViews();
    final String myEmail = mService.getIdentityStore().getIdentity().getEmail();
    boolean isMember = false;
    mSomebodyAnswered = false;
    for (MemberStatusTO ms : mCurrentMessage.members) {
        boolean showMember = true;
        View view = getLayoutInflater().inflate(R.layout.message_member_detail, null);
        // Set receiver avatar
        RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.avatar);
        rl.addView(createParticipantView(ms));
        // Set receiver name
        TextView receiverView = (TextView) view.findViewById(R.id.receiver);
        final String memberName = mFriendsPlugin.getName(ms.member);
        receiverView.setText(memberName == null ? sender : memberName);
        // Set received timestamp
        TextView receivedView = (TextView) view.findViewById(R.id.received_timestamp);
        if ((ms.status & MessagingPlugin.STATUS_RECEIVED) == MessagingPlugin.STATUS_RECEIVED) {
            final String humanTime = TimeUtils.getDayTimeStr(this, ms.received_timestamp * 1000);
            if (ms.member.equals(mCurrentMessage.sender))
                receivedView.setText(getString(R.string.sent_at, humanTime));
            else
                receivedView.setText(getString(R.string.received_at, humanTime));
        } else {
            receivedView.setText(R.string.not_yet_received);
        }
        // Set replied timestamp
        TextView repliedView = (TextView) view.findViewById(R.id.acked_timestamp);
        if ((ms.status & MessagingPlugin.STATUS_ACKED) == MessagingPlugin.STATUS_ACKED) {
            mSomebodyAnswered = true;
            String acked_timestamp = TimeUtils.getDayTimeStr(this, ms.acked_timestamp * 1000);
            if (ms.button_id != null) {

                ButtonTO button = null;
                for (ButtonTO b : mCurrentMessage.buttons) {
                    if (b.id.equals(ms.button_id)) {
                        button = b;
                        break;
                    }
                }
                if (button == null) {
                    repliedView.setText(getString(R.string.dismissed_at, acked_timestamp));
                    // Do not show sender as member if he hasn't clicked a
                    // button
                    showMember = !ms.member.equals(mCurrentMessage.sender);
                } else {
                    repliedView.setText(getString(R.string.replied_at, button.caption, acked_timestamp));
                }
            } else {
                if (ms.custom_reply == null) {
                    // Do not show sender as member if he hasn't clicked a
                    // button
                    showMember = !ms.member.equals(mCurrentMessage.sender);
                    repliedView.setText(getString(R.string.dismissed_at, acked_timestamp));
                } else
                    repliedView.setText(getString(R.string.replied_at, ms.custom_reply, acked_timestamp));
            }
        } else {
            repliedView.setText(R.string.not_yet_replied);
            showMember = !ms.member.equals(mCurrentMessage.sender);
        }
        if (br != null && br.scheme == ColorScheme.dark) {
            receiverView.setTextColor(darkSchemeTextColor);
            receivedView.setTextColor(darkSchemeTextColor);
            repliedView.setTextColor(darkSchemeTextColor);
        } else {
            receiverView.setTextColor(lightSchemeTextColor);
            receivedView.setTextColor(lightSchemeTextColor);
            repliedView.setTextColor(lightSchemeTextColor);
        }

        if (showMember)
            members.addView(view);
        isMember |= ms.member.equals(myEmail);
    }

    boolean isLocked = (mCurrentMessage.flags & MessagingPlugin.FLAG_LOCKED) == MessagingPlugin.FLAG_LOCKED;
    boolean canEdit = isMember && !isLocked;

    // Add attachments
    LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachment_layout);
    attachmentLayout.removeAllViews();
    if (mCurrentMessage.attachments.length > 0) {
        attachmentLayout.setVisibility(View.VISIBLE);

        for (final AttachmentTO attachment : mCurrentMessage.attachments) {
            View v = getLayoutInflater().inflate(R.layout.attachment_item, null);

            ImageView attachment_image = (ImageView) v.findViewById(R.id.attachment_image);
            if (AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(attachment.content_type)
                    || AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_img);
            } else if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_pdf);
            } else if (AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4
                    .equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_video);
            } else {
                attachment_image.setImageResource(R.drawable.attachment_unknown);
                L.d("attachment.content_type not known: " + attachment.content_type);
            }

            TextView attachment_text = (TextView) v.findViewById(R.id.attachment_text);
            attachment_text.setText(attachment.name);

            v.setOnClickListener(new SafeViewOnClickListener() {

                @Override
                public void safeOnClick(View v) {
                    String downloadUrlHash = mMessagingPlugin
                            .attachmentDownloadUrlHash(attachment.download_url);

                    File attachmentsDir;
                    try {
                        attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), null);
                    } catch (IOException e) {
                        L.d("Unable to create attachment directory", e);
                        UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                R.string.unable_to_read_write_sd_card);
                        return;
                    }

                    boolean attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir,
                            downloadUrlHash);

                    if (!attachmentAvailable) {
                        try {
                            attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(),
                                    mCurrentMessage.key);
                        } catch (IOException e) {
                            L.d("Unable to create attachment directory", e);
                            UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                    R.string.unable_to_read_write_sd_card);
                            return;
                        }

                        attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir,
                                downloadUrlHash);
                    }

                    if (!mService.getNetworkConnectivityManager().isConnected() && !attachmentAvailable) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ServiceMessageDetailActivity.this);
                        builder.setMessage(R.string.no_internet_connection_try_again);
                        builder.setPositiveButton(R.string.rogerthat, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        return;
                    }
                    if (IOUtils.shouldCheckExternalStorageAvailable()) {
                        String state = Environment.getExternalStorageState();
                        if (Environment.MEDIA_MOUNTED.equals(state)) {
                            // Its all oke
                        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                            if (!attachmentAvailable) {
                                L.d("Unable to write to sd-card");
                                UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                        R.string.unable_to_read_write_sd_card);
                                return;
                            }
                        } else {
                            L.d("Unable to read or write to sd-card");
                            UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                    R.string.unable_to_read_write_sd_card);
                            return;
                        }
                    }

                    L.d("attachment.content_type: " + attachment.content_type);
                    L.d("attachment.download_url: " + attachment.download_url);
                    L.d("attachment.name: " + attachment.name);
                    L.d("attachment.size: " + attachment.size);

                    if (AttachmentViewerActivity.supportsContentType(attachment.content_type)) {
                        Intent i = new Intent(ServiceMessageDetailActivity.this,
                                AttachmentViewerActivity.class);
                        i.putExtra("thread_key", mCurrentMessage.getThreadKey());
                        i.putExtra("message", mCurrentMessage.key);
                        i.putExtra("content_type", attachment.content_type);
                        i.putExtra("download_url", attachment.download_url);
                        i.putExtra("name", attachment.name);
                        i.putExtra("download_url_hash", downloadUrlHash);

                        startActivity(i);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ServiceMessageDetailActivity.this);
                        builder.setMessage(getString(R.string.attachment_can_not_be_displayed_in_your_version,
                                getString(R.string.app_name)));
                        builder.setPositiveButton(R.string.rogerthat, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                }

            });

            attachmentLayout.addView(v);
        }

    } else {
        attachmentLayout.setVisibility(View.GONE);
    }

    LinearLayout widgetLayout = (LinearLayout) findViewById(R.id.widget_layout);
    if (mCurrentMessage.form == null) {
        widgetLayout.setVisibility(View.GONE);
    } else {
        widgetLayout.setVisibility(View.VISIBLE);
        widgetLayout.setEnabled(canEdit);
        displayWidget(widgetLayout, br);
    }

    // Add buttons
    TableLayout tableLayout = (TableLayout) findViewById(R.id.buttons);
    tableLayout.removeAllViews();

    for (final ButtonTO button : mCurrentMessage.buttons) {
        addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button);
    }
    if (mCurrentMessage.form == null && (mCurrentMessage.flags
            & MessagingPlugin.FLAG_ALLOW_DISMISS) == MessagingPlugin.FLAG_ALLOW_DISMISS) {
        ButtonTO button = new ButtonTO();
        button.caption = "Roger that!";
        addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button);
    }

    if (mCurrentMessage.broadcast_type != null) {
        L.d("Show broadcast spam control");
        final RelativeLayout broadcastSpamControl = (RelativeLayout) findViewById(R.id.broadcast_spam_control);
        View broadcastSpamControlBorder = findViewById(R.id.broadcast_spam_control_border);
        final View broadcastSpamControlDivider = findViewById(R.id.broadcast_spam_control_divider);

        final LinearLayout broadcastSpamControlTextContainer = (LinearLayout) findViewById(
                R.id.broadcast_spam_control_text_container);
        TextView broadcastSpamControlText = (TextView) findViewById(R.id.broadcast_spam_control_text);

        final LinearLayout broadcastSpamControlSettingsContainer = (LinearLayout) findViewById(
                R.id.broadcast_spam_control_settings_container);
        TextView broadcastSpamControlSettingsText = (TextView) findViewById(
                R.id.broadcast_spam_control_settings_text);
        TextView broadcastSpamControlIcon = (TextView) findViewById(R.id.broadcast_spam_control_icon);
        broadcastSpamControlIcon.setTypeface(mFontAwesomeTypeFace);
        broadcastSpamControlIcon.setText(R.string.fa_bell);

        final FriendBroadcastInfo fbi = mFriendsPlugin.getFriendBroadcastFlowForMfr(mCurrentMessage.sender);
        if (fbi == null) {
            L.bug("BroadcastData was null for: " + mCurrentMessage.sender);
            collapseDetails(DETAIL_SECTIONS);
            return;
        }
        broadcastSpamControl.setVisibility(View.VISIBLE);

        broadcastSpamControlSettingsContainer.setOnClickListener(new SafeViewOnClickListener() {

            @Override
            public void safeOnClick(View v) {
                L.d("goto broadcast settings");

                PressMenuIconRequestTO request = new PressMenuIconRequestTO();
                request.coords = fbi.coords;
                request.static_flow_hash = fbi.staticFlowHash;
                request.hashed_tag = fbi.hashedTag;
                request.generation = fbi.generation;
                request.service = mCurrentMessage.sender;
                mContext = "MENU_" + UUID.randomUUID().toString();
                request.context = mContext;
                request.timestamp = System.currentTimeMillis() / 1000;

                showTransmitting(null);
                Map<String, Object> userInput = new HashMap<String, Object>();
                userInput.put("request", request.toJSONMap());
                userInput.put("func", "com.mobicage.api.services.pressMenuItem");

                MessageFlowRun mfr = new MessageFlowRun();
                mfr.staticFlowHash = fbi.staticFlowHash;
                try {
                    JsMfr.executeMfr(mfr, userInput, mService, true);
                } catch (EmptyStaticFlowException ex) {
                    completeTransmit(null);
                    AlertDialog.Builder builder = new AlertDialog.Builder(ServiceMessageDetailActivity.this);
                    builder.setMessage(ex.getMessage());
                    builder.setPositiveButton(R.string.rogerthat, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return;
                }
            }

        });

        UIUtils.showHint(this, mService, HINT_BROADCAST, R.string.hint_broadcast,
                mCurrentMessage.broadcast_type, mFriendsPlugin.getName(mCurrentMessage.sender));

        broadcastSpamControlText
                .setText(getString(R.string.broadcast_subscribed_to, mCurrentMessage.broadcast_type));
        broadcastSpamControlSettingsText.setText(fbi.label);
        int ligthAlpha = 180;
        int darkAlpha = 70;
        int alpha = ligthAlpha;
        if (br != null && br.scheme == ColorScheme.dark) {
            broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.black));
            broadcastSpamControlBorder.setBackgroundColor(darkSchemeTextColor);
            broadcastSpamControlDivider.setBackgroundColor(darkSchemeTextColor);
            activity.setBackgroundColor(darkSchemeTextColor);
            broadcastSpamControlText.setTextColor(lightSchemeTextColor);
            broadcastSpamControlSettingsText.setTextColor(lightSchemeTextColor);
            int alpacolor = Color.argb(darkAlpha, Color.red(lightSchemeTextColor),
                    Color.green(lightSchemeTextColor), Color.blue(lightSchemeTextColor));
            broadcastSpamControl.setBackgroundColor(alpacolor);

            alpha = darkAlpha;
        } else {
            broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.white));
            broadcastSpamControlBorder.setBackgroundColor(lightSchemeTextColor);
            broadcastSpamControlDivider.setBackgroundColor(lightSchemeTextColor);
            activity.setBackgroundColor(lightSchemeTextColor);
            broadcastSpamControlText.setTextColor(darkSchemeTextColor);
            broadcastSpamControlSettingsText.setTextColor(darkSchemeTextColor);
            int alpacolor = Color.argb(darkAlpha, Color.red(darkSchemeTextColor),
                    Color.green(darkSchemeTextColor), Color.blue(darkSchemeTextColor));
            broadcastSpamControl.setBackgroundColor(alpacolor);
        }

        if (br != null && br.color != null) {
            int alphaColor = Color.argb(alpha, Color.red(br.color), Color.green(br.color),
                    Color.blue(br.color));
            broadcastSpamControl.setBackgroundColor(alphaColor);
        }

        mService.postOnUIHandler(new SafeRunnable() {

            @Override
            protected void safeRun() throws Exception {
                int maxHeight = broadcastSpamControl.getHeight();
                broadcastSpamControlDivider.getLayoutParams().height = maxHeight;
                broadcastSpamControlDivider.requestLayout();

                broadcastSpamControlSettingsContainer.getLayoutParams().height = maxHeight;
                broadcastSpamControlSettingsContainer.requestLayout();

                broadcastSpamControlTextContainer.getLayoutParams().height = maxHeight;
                broadcastSpamControlTextContainer.requestLayout();

                int broadcastSpamControlWidth = broadcastSpamControl.getWidth();
                android.view.ViewGroup.LayoutParams lp = broadcastSpamControlSettingsContainer
                        .getLayoutParams();
                lp.width = broadcastSpamControlWidth / 4;
                broadcastSpamControlSettingsContainer.setLayoutParams(lp);
            }
        });
    }

    if (!isUpdate)
        collapseDetails(DETAIL_SECTIONS);
}

From source file:terse.a1.TerseActivity.java

private void viewPath9display(String path, LayoutParams widgetParams) {
    String explain;/*from   w w w  . j  a v a  2 s  .  co  m*/
    if (terp_error != null) {
        explain = "terp_error = " + terp_error;
    } else {
        try {
            terp.say("Sending to terp: %s", path);
            final Dict d = terp.handleUrl(path, taQuery);
            explain = "DEFAULT EXPLANATION:\n\n" + d.toString();

            Str TYPE = d.cls.terp.newStr("type");
            Str VALUE = d.cls.terp.newStr("value");
            Str TITLE = d.cls.terp.newStr("title");
            Str type = (Str) d.dict.get(TYPE);
            Ur value = d.dict.get(VALUE);
            Ur title = d.dict.get(TITLE);

            // {
            // double ticks = Static.floatAt(d, "ticks", -1);
            // double nanos = Static.floatAt(d, "nanos", -1);
            // Toast.makeText(
            // getApplicationContext(),
            // Static.fmt("%d ticks, %.3f secs", (long) ticks,
            // (double) nanos / 1e9), Toast.LENGTH_SHORT)
            // .show();
            // }

            if (type.str.equals("list") && value instanceof Vec) {
                final ArrayList<Ur> v = ((Vec) value).vec;
                final ArrayList<String> labels = new ArrayList<String>();
                final ArrayList<String> links = new ArrayList<String>();
                for (int i = 0; i < v.size(); i++) {
                    Ur item = v.get(i);
                    String label = item instanceof Str ? ((Str) item).str : item.toString();
                    if (item instanceof Vec && ((Vec) item).vec.size() == 2) {
                        // OLD STYLE
                        label = ((Vec) item).vec.get(0).toString();
                        Matcher m = LINK_P.matcher(label);
                        if (m.lookingAt()) {
                            label = m.group(2) + " " + m.group(3);
                        }
                        label += "    [" + ((Vec) item).vec.get(1).toString().length() + "]";
                        links.add(null); // Use old style, not links.
                    } else {
                        // NEW STYLE
                        label = item.toString();
                        if (label.charAt(0) == '/') {
                            String link = Terp.WHITE_PLUS.split(label, 2)[0];
                            links.add(link);
                        } else {
                            links.add("");
                        }
                    }
                    labels.add(label);
                }
                if (labels.size() != links.size())
                    terp.toss("lables#%d links#%d", labels.size(), links.size());

                ListView listv = new ListView(this);
                listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels));
                listv.setLayoutParams(widgetParams);
                listv.setTextFilterEnabled(true);

                listv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // When clicked, show a toast with the TextView text
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                        String toast_text = ((TextView) view).getText().toString();
                        // if (v.get(position) instanceof Vec) {
                        if (links.get(position) == null) {
                            // OLD STYLE
                            Vec pair = (Vec) v.get(position);
                            if (pair.vec.size() == 2) {
                                if (pair.vec.get(0) instanceof Str) {
                                    String[] words = ((Str) pair.vec.get(0)).str.split("\\|");
                                    Log.i("TT-WORDS", terp.arrayToString(words));
                                    toast_text += "\n\n" + Static.arrayToString(words);
                                    if (words[1].equals("link")) {
                                        Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build();
                                        Intent intent = new Intent("android.intent.action.MAIN", uri);
                                        intent.setClass(getApplicationContext(), TerseActivity.class);

                                        startActivity(intent);
                                    }
                                }
                            }
                        } else {
                            // NEW STYLE
                            terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position,
                                    links.get(position), labels.get(position));
                            if (links.get(position).length() > 0) {
                                Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build();
                                Intent intent = new Intent("android.intent.action.MAIN", uri);
                                intent.setClass(getApplicationContext(), TerseActivity.class);

                                startActivity(intent);
                            }
                        }
                        // }
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                    }
                });
                setContentView(listv);
                return;
            } else if (type.str.equals("edit") && value instanceof Str) {
                final EditText ed = new EditText(this);

                ed.setText(taSaveMe == null ? value.toString() : taSaveMe);

                ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE
                        | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                ed.setLayoutParams(widgetParams);
                // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                ed.setTextAppearance(this, R.style.teletype);
                ed.setBackgroundColor(Color.BLACK);
                ed.setGravity(Gravity.TOP);
                ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
                ed.setVerticalFadingEdgeEnabled(true);
                ed.setVerticalScrollBarEnabled(true);
                ed.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter"
                        // button
                        // if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        // &&
                        // (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        // // Perform action on key press
                        // Toast.makeText(TerseActivity.this, ed.getText(),
                        // Toast.LENGTH_SHORT).show();
                        // return true;
                        // }
                        return false;
                    }
                });

                Button btn = new Button(this);
                btn.setText("Save");
                btn.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // Perform action on clicks
                        String text = ed.getText().toString();
                        text = Parser.charSubsts(text);
                        Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show();
                        String action = stringAt(d, "action");
                        String query = "";

                        String f1 = stringAt(d, "field1");
                        String v1 = stringAt(d, "value1");
                        String f2 = stringAt(d, "field2");
                        String v2 = stringAt(d, "value2");
                        f1 = (f1 == null) ? "f1null" : f1;
                        v1 = (v1 == null) ? "v1null" : v1;
                        f2 = (f2 == null) ? "f2null" : f2;
                        v2 = (v2 == null) ? "v2null" : v2;

                        startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"),
                                stringAt(d, "field2"), stringAt(d, "value2"), "text", text);
                    }
                });

                LinearLayout linear = new LinearLayout(this);
                linear.setOrientation(LinearLayout.VERTICAL);
                linear.addView(btn);
                linear.addView(ed);
                setContentView(linear);
                return;

            } else if (type.str.equals("draw") && value instanceof Vec) {
                Vec v = ((Vec) value);
                DrawView dv = new DrawView(this, v.vec, d);
                dv.setLayoutParams(widgetParams);
                setContentView(dv);
                return;
            } else if (type.str.equals("live")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                TerseSurfView tsv = new TerseSurfView(this, blk, event);
                setContentView(tsv);
                return;
            } else if (type.str.equals("fnord")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                FnordView fnord = new FnordView(this, blk, event);
                setContentView(fnord);
                return;
            } else if (type.str.equals("world") && value instanceof Str) {
                String newWorld = value.toString();
                if (Terp.WORLD_P.matcher(newWorld).matches()) {
                    world = newWorld;
                    resetTerp();
                    explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world);
                    Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show();
                } else {
                    terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld);
                }
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("text")) {
                explain = "<<< " + title + " >>>\n\n" + value.toString();
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("html")) {
                final WebView webview = new WebView(this);
                // webview.loadData(value.toString(), "text/html", null);
                webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null);
                webview.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // terp.say("WebView UrlLoading: url=%s", url);
                        URI uri = URI.create("" + url);
                        // terp.say("WebView UrlLoading: URI=%s", uri);
                        terp.say("WebView UrlLoading: getPath=%s", uri.getPath());
                        terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery());

                        // Toast.makeText(getApplicationContext(),
                        // uri.toASCIIString(), Toast.LENGTH_SHORT)
                        // .show();
                        // webview.invalidate();
                        //
                        // TextView quick = new
                        // TextView(TerseActivity.this);
                        // quick.setText(uri.toASCIIString());
                        // quick.setBackgroundColor(Color.BLACK);
                        // quick.setTextColor(Color.WHITE);
                        // setContentView(quick);

                        startTerseActivity(uri.getPath(), uri.getQuery());

                        return true;
                    }
                });

                // webview.setWebChromeClient(new WebChromeClient());
                webview.getSettings().setBuiltInZoomControls(true);
                // webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setDefaultFontSize(18);
                webview.getSettings().setNeedInitialFocus(true);
                webview.getSettings().setSupportZoom(true);
                webview.getSettings().setSaveFormData(true);
                setContentView(webview);

                // ScrollView scrollv = new ScrollView(this);
                // scrollv.addView(webview);
                // setContentView(scrollv);
                return;
            } else {
                explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls
                        + "\n\n##############\n\n";
                explain += value.toString();
                // Fall thru for explainv.setText(explain).
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            explain = Static.describe(ex);
        }
    }

    TextView explainv = new TextView(this);
    explainv.setText(explain);
    explainv.setBackgroundColor(Color.BLACK);
    explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
    explainv.setTextColor(Color.YELLOW);

    SetContentViewWithHomeButtonAndScroll(explainv);
}

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

private WebView createWebView() {
    WebView webView = new MyWebView(this);
    webView.setWillNotCacheDrawing(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    if (mZoomEnabled) {
        webView.getSettings().setBuiltInZoomControls(true);
    }/*  www  .  ja v a  2 s.  com*/
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new AnkiDroidWebChromeClient());
    webView.addJavascriptInterface(new JavaScriptInterface(this), "ankidroid");
    if (AnkiDroidApp.SDK_VERSION > 7) {
        webView.setFocusableInTouchMode(false);
    }
    AnkiDroidApp.getCompat().setScrollbarFadingEnabled(webView, mPrefFadeScrollbars);
    Log.i(AnkiDroidApp.TAG, "Focusable = " + webView.isFocusable() + ", Focusable in touch mode = "
            + webView.isFocusableInTouchMode());

    return webView;
}

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

private WebView createWebView() {
    WebView webView = new MyWebView(this);
    webView.setWillNotCacheDrawing(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    if (mZoomEnabled) {
        webView.getSettings().setBuiltInZoomControls(true);
    }/*from   w  ww. j  av  a2s  . c o m*/
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new AnkiDroidWebChromeClient());
    webView.addJavascriptInterface(new JavaScriptInterface(this), "ankidroid");
    if (AnkiDroidApp.SDK_VERSION > 7) {
        webView.setFocusableInTouchMode(false);
    }
    AnkiDroidApp.getCompat().setScrollbarFadingEnabled(webView, mPrefFadeScrollbars);
    // Log.i(AnkiDroidApp.TAG, "Focusable = " + webView.isFocusable() + ", Focusable in touch mode = " + webView.isFocusableInTouchMode());

    return webView;
}

From source file:ar.com.tristeslostrestigres.diasporanativewebapp.MainActivity.java

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

    progressBar = findViewById(R.id.progressBar);

    pm = new PrefManager(MainActivity.this);

    SharedPreferences config = getSharedPreferences("PodSettings", MODE_PRIVATE);
    podDomain = config.getString("podDomain", null);

    fab = findViewById(R.id.multiple_actions);
    fab.setVisibility(View.GONE);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from  w  w w  .  j  a  va2 s. c  o  m*/
    getSupportActionBar().setTitle(null);

    txtTitle = (TextView) findViewById(R.id.toolbar_title);
    txtTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Helpers.isOnline(MainActivity.this)) {
                txtTitle.setText(R.string.jb_stream);
                webView.loadUrl("https://" + podDomain + "/stream");
            } else {
                Snackbar.make(v, R.string.no_internet, Snackbar.LENGTH_SHORT).show();
            }
        }
    });

    webView = findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.addJavascriptInterface(new JavaScriptInterface(), "NotificationCounter");

    if (savedInstanceState != null) {
        webView.restoreState(savedInstanceState);
    }

    wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setUseWideViewPort(true);
    wSettings.setLoadWithOverviewMode(true);
    wSettings.setDomStorageEnabled(true);
    wSettings.setMinimumFontSize(pm.getMinimumFontSize());
    wSettings.setLoadsImagesAutomatically(pm.getLoadImages());

    if (android.os.Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;
        }

        public void onPageFinished(WebView view, String url) {
            if (url.contains("/new") || url.contains("/sign_in")) {
                fab.setVisibility(View.GONE);
            } else {
                fab.setVisibility(View.VISIBLE);
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage(description).setPositiveButton("CLOSE", null).show();
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.hideTopBar(wv);
                fab.setVisibility(View.VISIBLE);
            }

            if (progress == 100) {
                fab.collapse();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.drawer), "Unable to get image",
                            Snackbar.LENGTH_SHORT).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    });

    /*
     * NavigationView
     */
    NavigationView navigationView = findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            drawerLayout.closeDrawers();

            switch (menuItem.getItemId()) {
            default:
                Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                        Snackbar.LENGTH_SHORT).show();
                return true;

            case R.id.jb_stream:
                if (Helpers.isOnline(MainActivity.this)) {
                    txtTitle.setText(R.string.jb_stream);
                    webView.loadUrl("https://" + podDomain + "/stream");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_public:
                setTitle(R.string.jb_public);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/public");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_liked:
                txtTitle.setText(R.string.jb_liked);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/liked");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_commented:
                txtTitle.setText(R.string.jb_commented);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/commented");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_contacts:
                txtTitle.setText(R.string.jb_contacts);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/contacts");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_mentions:
                txtTitle.setText(R.string.jb_mentions);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/mentions");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_activities:
                txtTitle.setText(R.string.jb_activities);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/activity");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_followed_tags:
                txtTitle.setText(R.string.jb_followed_tags);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/followed_tags");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_manage_tags:

                txtTitle.setText(R.string.jb_manage_tags);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/tag_followings/manage");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_license:
                txtTitle.setText(R.string.jb_license);
                new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.license_title))
                        .setMessage(getString(R.string.license_text))
                        .setPositiveButton(getString(R.string.license_yes),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        Intent i = new Intent(Intent.ACTION_VIEW,
                                                Uri.parse("https://github.com/mdev88/Diaspora-Native-WebApp"));
                                        startActivity(i);
                                        dialog.cancel();
                                    }
                                })
                        .setNegativeButton(getString(R.string.license_no),
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                })
                        .show();

                return true;

            case R.id.jb_aspects:
                txtTitle.setText(R.string.jb_aspects);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/aspects");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }

            case R.id.jb_settings:
                txtTitle.setText(R.string.jb_settings);
                if (Helpers.isOnline(MainActivity.this)) {
                    webView.loadUrl("https://" + podDomain + "/user/edit");
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();

                    return false;
                }

            case R.id.jb_pod:
                txtTitle.setText(R.string.jb_pod);
                if (Helpers.isOnline(MainActivity.this)) {
                    new AlertDialog.Builder(MainActivity.this).setTitle(getString(R.string.confirmation))
                            .setMessage(getString(R.string.change_pod_warning))
                            .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                                @TargetApi(11)
                                public void onClick(DialogInterface dialog, int id) {
                                    webView.clearCache(true);
                                    dialog.cancel();
                                    Intent i = new Intent(MainActivity.this, PodsActivity.class);
                                    startActivity(i);
                                    finish();
                                }
                            }).setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                                @TargetApi(11)
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            }).show();
                    return true;
                } else {
                    Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet,
                            Snackbar.LENGTH_SHORT).show();
                    return false;
                }
            }
        }
    });

    /*
     * DrawerLayout
     */
    drawerLayout = findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer);
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    //calling sync state is necessary or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();

    if (savedInstanceState == null) {
        if (Helpers.isOnline(MainActivity.this)) {
            webView.loadData("", "text/html", null);
            webView.loadUrl("https://" + podDomain);
        } else {
            Snackbar.make(getWindow().findViewById(R.id.drawer), R.string.no_internet, Snackbar.LENGTH_SHORT)
                    .show();
        }
    }

}

From source file:com.sentaroh.android.SMBSync2.ActivityMain.java

@SuppressLint("InflateParams")
private void aboutSMBSync() {
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.about_dialog);

    final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.about_dialog_title_view);
    final TextView title = (TextView) dialog.findViewById(R.id.about_dialog_title);
    title_view.setBackgroundColor(mGp.themeColorList.dialog_title_background_color);
    title.setTextColor(mGp.themeColorList.text_color_dialog_title);
    title.setText(getString(R.string.msgs_dlg_title_about) + "(Ver " + packageVersionName + ")");

    // get our tabHost from the xml
    final TabHost tab_host = (TabHost) dialog.findViewById(R.id.about_tab_host);
    tab_host.setup();//www .  j  a va 2s .  c  om

    final TabWidget tab_widget = (TabWidget) dialog.findViewById(android.R.id.tabs);

    if (Build.VERSION.SDK_INT >= 11) {
        tab_widget.setStripEnabled(false);
        tab_widget.setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
    }

    CustomTabContentView tabViewProf = new CustomTabContentView(this,
            getString(R.string.msgs_about_dlg_func_btn));
    tab_host.addTab(tab_host.newTabSpec("func").setIndicator(tabViewProf).setContent(android.R.id.tabcontent));

    CustomTabContentView tabViewHist = new CustomTabContentView(this,
            getString(R.string.msgs_about_dlg_change_btn));
    tab_host.addTab(
            tab_host.newTabSpec("change").setIndicator(tabViewHist).setContent(android.R.id.tabcontent));

    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout ll_func = (LinearLayout) vi.inflate(R.layout.about_dialog_func, null);
    LinearLayout ll_change = (LinearLayout) vi.inflate(R.layout.about_dialog_change, null);

    final WebView func_view = (WebView) ll_func.findViewById(R.id.about_dialog_function);
    func_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_dlg_title_about_func_desc));
    func_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    func_view.getSettings().setBuiltInZoomControls(true);

    final WebView change_view = (WebView) ll_change.findViewById(R.id.about_dialog_change_history);
    change_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_dlg_title_about_change_desc));
    change_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    change_view.getSettings().setBuiltInZoomControls(true);

    final CustomViewPagerAdapter mAboutViewPagerAdapter = new CustomViewPagerAdapter(this,
            new WebView[] { func_view, change_view });
    final CustomViewPager mAboutViewPager = (CustomViewPager) dialog.findViewById(R.id.about_view_pager);
    //       mMainViewPager.setBackgroundColor(mThemeColorList.window_color_background);
    mAboutViewPager.setAdapter(mAboutViewPagerAdapter);
    mAboutViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            //             util.addDebugMsg(2,"I","onPageSelected entered, pos="+position);
            tab_widget.setCurrentTab(position);
            tab_host.setCurrentTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            //             util.addDebugMsg(2,"I","onPageScrollStateChanged entered, state="+state);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //             util.addDebugMsg(2,"I","onPageScrolled entered, pos="+position);
        }
    });

    tab_host.setOnTabChangedListener(new OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            util.addDebugMsg(2, "I", "onTabchanged entered. tab=" + tabId);
            mAboutViewPager.setCurrentItem(tab_host.getCurrentTab());
        }
    });

    final Button btnOk = (Button) dialog.findViewById(R.id.about_dialog_btn_ok);

    CommonDialog.setDlgBoxSizeLimit(dialog, true);

    // OK?
    btnOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btnOk.performClick();
        }
    });

    dialog.show();
}

From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java

private void aboutSMBSync() {

    // common ??/*from w  w w. jav  a  2 s  .c o m*/
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.about_dialog);
    ((TextView) dialog.findViewById(R.id.about_dialog_title))
            .setText(getString(R.string.msgs_dlg_title_about) + "(Ver " + packageVersionName + ")");
    final WebView func_view = (WebView) dialog.findViewById(R.id.about_dialog_function);
    //      func_view.loadDataWithBaseURL("file:///android_asset/",
    //            getString(R.string.msgs_dlg_title_about_func_desc),"text/html","UTF-8","");
    func_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_dlg_title_about_func_desc));
    func_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    func_view.getSettings().setBuiltInZoomControls(true);

    final WebView change_view = (WebView) dialog.findViewById(R.id.about_dialog_change_history);
    change_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_dlg_title_about_change_desc));
    change_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    change_view.getSettings().setBuiltInZoomControls(true);

    final Button btnFunc = (Button) dialog.findViewById(R.id.about_dialog_btn_show_func);
    final Button btnChange = (Button) dialog.findViewById(R.id.about_dialog_btn_show_change);
    final Button btnOk = (Button) dialog.findViewById(R.id.about_dialog_btn_ok);

    func_view.setVisibility(TextView.VISIBLE);
    change_view.setVisibility(TextView.GONE);
    btnChange.setBackgroundResource(R.drawable.button_bg_color_selector);
    btnFunc.setBackgroundResource(R.drawable.button_bg_color_selector);
    btnChange.setTextColor(Color.DKGRAY);
    btnFunc.setTextColor(Color.GREEN);
    btnFunc.setEnabled(false);

    //      btnOk.setTextColor(Color.DKGRAY);
    //      btnOk.setTextColor(Color.GREEN);
    //      btnOk.setBackgroundResource(R.drawable.button_back_ground_color_selector);

    CommonDialog.setDlgBoxSizeLimit(dialog, true);

    // func?
    btnFunc.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            change_view.setVisibility(TextView.GONE);
            func_view.setVisibility(TextView.VISIBLE);
            CommonDialog.setDlgBoxSizeLimit(dialog, true);
            //            func_view.setEnabled(true);
            //            change_view.setEnabled(false);
            btnFunc.setTextColor(Color.GREEN);
            btnChange.setTextColor(Color.DKGRAY);
            btnChange.setEnabled(true);
            btnFunc.setEnabled(false);
        }
    });

    // change?
    btnChange.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            change_view.setVisibility(TextView.VISIBLE);
            func_view.setVisibility(TextView.GONE);
            CommonDialog.setDlgBoxSizeLimit(dialog, true);
            //            func_view.setEnabled(true);
            //            change_view.setEnabled(false);
            btnChange.setTextColor(Color.GREEN);
            btnFunc.setTextColor(Color.DKGRAY);
            btnChange.setEnabled(false);
            btnFunc.setEnabled(true);
        }
    });

    // OK?
    btnOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btnOk.performClick();
        }
    });
    //      dialog.setOnKeyListener(new DialogOnKeyListener(mContext));
    //      dialog.setCancelable(false);
    dialog.show();

}

From source file:eu.vranckaert.worktime.utils.donations.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button///from   w w w .  j av  a  2s.  com
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // get flattr values from xml config
    String projectUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_project_url");
    String flattrUrl = DonationsUtils.getResourceString(getActivity(), "donations__flattr_url");

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrl = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrl.setText(flattrScheme + flattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + projectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + flattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}