Example usage for android.webkit WebView WebView

List of usage examples for android.webkit WebView WebView

Introduction

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

Prototype

public WebView(Context context) 

Source Link

Document

Constructs a new WebView with an Activity Context object.

Usage

From source file:com.chatwingsdk.activities.CommunicationActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from  w  w w. ja v a2  s  .  co m
public void ensureWebViewAndSubscribeToChannels() {
    if (mCurrentCommunicationMode == null)
        return;
    // Check whether the web view is available or not.
    // If not, init it and load faye client. When loading finished,
    // this method will be recursively called. At that point,
    // the actual subscribe code will be executed.
    if (mWebView == null) {
        mNotSubscribeToChannels = true;
        mWebView = new WebView(this);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mWebView.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {

                LogUtils.v(consoleMessage.message() + " -- level " + consoleMessage.messageLevel()
                        + " -- From line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());

                //This workaround tries to fix issue webview is not subscribe successfully
                //when the screen is off, we cant listen for otto event since it's dead before that
                //this likely happens on development or very rare case in production
                if (consoleMessage.messageLevel().equals(ConsoleMessage.MessageLevel.ERROR)) {
                    mWebView = null;
                    mNotSubscribeToChannels = true;
                }
                return true;
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                if (url.equals(Constants.FAYE_CLIENT_URL)) {
                    // Recursively call this method,
                    // to execute subscribe code.
                    ensureWebViewAndSubscribeToChannels();
                }
            }
        });

        mWebView.loadUrl(Constants.FAYE_CLIENT_URL);
        return;
    }
    if (mNotSubscribeToChannels) {
        mNotSubscribeToChannels = false;
        mCurrentCommunicationMode.subscribeToChannels(mWebView);
    }
}

From source file:com.cloudexplorers.plugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 * // ww  w  . j a v a2s.  c om
 * @param url
 *          The url to load.
 * @param jsonObject
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         * 
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input...
                                                        // Makes the text
                                                        // NON-EDITABLE
            edittext.setOnKeyListener(new View.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)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);

            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setPluginsEnabled(true);

            webview.requestFocus();
            webview.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container
            // layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.nttec.everychan.chans.dvach.DvachModule.java

private void cssTest(String boardName, final CancellableTask task) throws Exception { /* =*.*= */
    class CSSCodeHolder {
        private volatile String cssCode = null;

        public synchronized void setCode(String code) {
            Logger.d(TAG, "set CSS code: " + code);
            if (cssCode == null)
                cssCode = code;//from w  w  w .j ava  2 s .  co  m
        }

        public boolean isSet() {
            return cssCode != null;
        }

        public String getCode() {
            return cssCode;
        }
    }
    class WebViewHolder {
        private WebView webView = null;
    }

    final CSSCodeHolder holder = new CSSCodeHolder();
    final WebViewHolder wv = new WebViewHolder();
    final String cssTest = HttpStreamer.getInstance().getStringFromUrl(
            getUsingUrl() + boardName + "/csstest.foo", HttpRequestModel.DEFAULT_GET, httpClient, null, task,
            false);
    long startTime = System.currentTimeMillis();

    Async.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            wv.webView = new WebView(MainApplication.getInstance());
            wv.webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onLoadResource(WebView view, String url) {
                    if (url.contains("?code=") && !task.isCancelled()) {
                        holder.setCode(url.substring(url.indexOf("?code=") + 6));
                    }
                }
            });
            wv.webView.loadDataWithBaseURL("http://127.0.0.1/csstest.foo", cssTest, "text/html", "UTF-8", "");
        }
    });

    while (!holder.isSet()) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > 5000)
            break;
        Thread.yield();
    }

    Async.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                wv.webView.stopLoading();
                wv.webView.clearCache(true);
                wv.webView.destroy();
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }
    });

    if (task != null && task.isCancelled())
        throw new InterruptedException("interrupted");
    String cssCode = holder.getCode();
    if (cssCode != null) {
        HttpStreamer.getInstance().getBytesFromUrl(getUsingUrl() + boardName + "/csstest.foo?code=" + cssCode,
                HttpRequestModel.DEFAULT_GET, httpClient, null, task, false);
    }
}

From source file:foam.jellyfish.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    try {/*www .  j  ava  2s .  c o m*/
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("linear-layout")) {
            LinearLayout v = new LinearLayout(ctx);
            v.setId(arr.getInt(1));
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            //v.setPadding(2,2,2,2);
            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(image);
                v.setImageBitmap(bitmap);
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });
            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx,
                    android.R.layout.simple_spinner_item, spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    try {
                        CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("nomadic")) {
            final int wid = arr.getInt(1);
            NomadicSurfaceView v = new NomadicSurfaceView(ctx, wid);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            parent.addView(v);
        }

        /*
                    if (type.equals("canvas")) {
        StarwispCanvas v = new StarwispCanvas(ctx);
        final int wid = arr.getInt(1);
        v.setId(wid);
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
        v.SetDrawList(arr.getJSONArray(3));
        parent.addView(v);
                    }
                
                    if (type.equals("camera-preview")) {
        PictureTaker pt = new PictureTaker();
        CameraPreview v = new CameraPreview(ctx,pt);
        final int wid = arr.getInt(1);
        v.setId(wid);
                
                
        //              LinearLayout.LayoutParams lp =
        //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);
                
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
                
        //                v.setLayoutParams(lp);
        parent.addView(v);
                    }
        */
        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:foam.mongoose.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    try {/*from  www . j a  v  a  2s .  c om*/
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("linear-layout")) {
            LinearLayout v = new LinearLayout(ctx);
            v.setId(arr.getInt(1));
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            //v.setPadding(2,2,2,2);
            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(image);
                v.setImageBitmap(bitmap);
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });
            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    try {
                        CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);

            //              LinearLayout.LayoutParams lp =
            //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            //                v.setLayoutParams(lp);
            parent.addView(v);
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:org.zeroxlab.zeroxbenchmark.Benchmark.java

private void initViews() {
        /*/* w w w .  ja v a 2  s  .  c o  m*/
        mRun = (Button)findViewById(R.id.btn_run);
        mRun.setOnClickListener(this);
            
        mShow = (Button)findViewById(R.id.btn_show);
        mShow.setOnClickListener(this);
        mShow.setClickable(false);
            
        mLinearLayout = (LinearLayout)findViewById(R.id.list_container);
        mMainView = (LinearLayout)findViewById(R.id.main_view);
            
        mBannerInfo = (TextView)findViewById(R.id.banner_info);
        mBannerInfo.setText("Hello!\nSelect cases to Run.\nUploaded results:\nhttp://0xbenchmark.appspot.com");
        */

        mTabHost = getTabHost();

        int length = mCases.size();
        mCheckList = new CheckBox[length];
        mDesc = new TextView[length];
        for (int i = 0; i < length; i++) {
            mCheckList[i] = new CheckBox(this);
            mCheckList[i].setText(mCases.get(i).getTitle());
            mDesc[i] = new TextView(this);
            mDesc[i].setText(mCases.get(i).getDescription());
            mDesc[i].setTextSize(mDesc[i].getTextSize() - 2);
            mDesc[i].setPadding(42, 0, 10, 10);
        }

        TabContentFactory mTCF = new TabContentFactory() {
            public View createTabContent(String tag) {
                ViewGroup.LayoutParams fillParent = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                        ViewGroup.LayoutParams.FILL_PARENT);
                ViewGroup.LayoutParams fillWrap = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                LinearLayout.LayoutParams wrapContent = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                wrapContent.gravity = Gravity.CENTER;
                LinearLayout.LayoutParams weightedFillWrap = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                weightedFillWrap.weight = 1;

                if (tag.equals(MAIN)) {
                    LinearLayout mMainView = new LinearLayout(Benchmark.this);
                    mMainView.setOrientation(1);
                    ScrollView mListScroll = new ScrollView(Benchmark.this);

                    LinearLayout mMainViewContainer = new LinearLayout(Benchmark.this);
                    mMainViewContainer.setOrientation(1);
                    ImageView mIconView = new ImageView(Benchmark.this);
                    mIconView.setImageResource(R.drawable.icon);

                    TextView mBannerInfo = new TextView(Benchmark.this);
                    mBannerInfo.setText("0xbench\nSelect benchmarks in the tabs,\nor batch select:");

                    d2CheckBox = new CheckBox(Benchmark.this);
                    d2CheckBox.setText(D2);
                    d2CheckBox.setOnClickListener(Benchmark.this);

                    d3CheckBox = new CheckBox(Benchmark.this);
                    d3CheckBox.setText(D3);
                    d3CheckBox.setOnClickListener(Benchmark.this);

                    mathCheckBox = new CheckBox(Benchmark.this);
                    mathCheckBox.setText(MATH);
                    mathCheckBox.setOnClickListener(Benchmark.this);

                    vmCheckBox = new CheckBox(Benchmark.this);
                    vmCheckBox.setText(VM);
                    vmCheckBox.setOnClickListener(Benchmark.this);

                    nativeCheckBox = new CheckBox(Benchmark.this);
                    nativeCheckBox.setText(NATIVE);
                    nativeCheckBox.setOnClickListener(Benchmark.this);

                    miscCheckBox = new CheckBox(Benchmark.this);
                    miscCheckBox.setText(MISC);
                    miscCheckBox.setOnClickListener(Benchmark.this);

                    TextView mWebInfo = new TextView(Benchmark.this);
                    mWebInfo.setText("Uploaded results:\nhttp://0xbenchmark.appspot.com");

                    LinearLayout mButtonContainer = new LinearLayout(Benchmark.this);
                    mRun = new Button(Benchmark.this);
                    mShow = new Button(Benchmark.this);
                    mRun.setText("Run");
                    mShow.setText("Show");
                    mRun.setOnClickListener(Benchmark.this);
                    mShow.setOnClickListener(Benchmark.this);
                    mButtonContainer.addView(mRun, weightedFillWrap);
                    mButtonContainer.addView(mShow, weightedFillWrap);
                    WebView mTracker = new WebView(Benchmark.this);
                    mTracker.clearCache(true);
                    mTracker.setWebViewClient(new WebViewClient() {
                        public void onPageFinished(WebView view, String url) {
                            Log.i(TAG, "Tracker: " + view.getTitle() + " -> " + url);
                        }

                        public void onReceivedError(WebView view, int errorCode, String description,
                                String failingUrl) {
                            Log.e(TAG, "Track err: " + description);
                        }
                    });
                    mTracker.loadUrl(trackerUrl);
                    mMainViewContainer.addView(mIconView, wrapContent);
                    mMainViewContainer.addView(mBannerInfo);
                    mMainViewContainer.addView(mathCheckBox);
                    mMainViewContainer.addView(d2CheckBox);
                    mMainViewContainer.addView(d3CheckBox);
                    mMainViewContainer.addView(vmCheckBox);
                    mMainViewContainer.addView(nativeCheckBox);
                    mMainViewContainer.addView(miscCheckBox);
                    mMainViewContainer.addView(mWebInfo);
                    mMainViewContainer.addView(mButtonContainer, fillWrap);
                    mMainViewContainer.addView(mTracker, 0, 0);
                    mListScroll.addView(mMainViewContainer, fillParent);
                    mMainView.addView(mListScroll, fillWrap);

                    return mMainView;

                }

                LinearLayout mMainView = new LinearLayout(Benchmark.this);
                mMainView.setOrientation(1);
                ScrollView mListScroll = new ScrollView(Benchmark.this);
                LinearLayout mListContainer = new LinearLayout(Benchmark.this);
                mListContainer.setOrientation(1);
                mListScroll.addView(mListContainer, fillParent);
                mMainView.addView(mListScroll, fillWrap);

                boolean gray = true;
                int length = mCases.size();
                Log.i(TAG, "L: " + length);
                Log.i(TAG, "TCF: " + tag);
                for (int i = 0; i < length; i++) {
                    if (!mCategory.get(tag).contains(mCases.get(i)))
                        continue;
                    Log.i(TAG, "Add: " + i);
                    mListContainer.addView(mCheckList[i], fillWrap);
                    mListContainer.addView(mDesc[i], fillWrap);
                    if (gray) {
                        int color = 0xFF333333; //ARGB
                        mCheckList[i].setBackgroundColor(color);
                        mDesc[i].setBackgroundColor(color);
                    }
                    gray = !gray;
                }
                return mMainView;
            }
        };

        mTabHost.addTab(mTabHost.newTabSpec(MAIN).setIndicator(MAIN, getResources().getDrawable(R.drawable.ic_eye))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(D2).setIndicator(D2, getResources().getDrawable(R.drawable.ic_2d))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(D3).setIndicator(D3, getResources().getDrawable(R.drawable.ic_3d))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(MATH).setIndicator(MATH, getResources().getDrawable(R.drawable.ic_pi))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(VM).setIndicator(VM, getResources().getDrawable(R.drawable.ic_vm))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(NATIVE)
                .setIndicator(NATIVE, getResources().getDrawable(R.drawable.ic_c)).setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(MISC).setIndicator(MISC, getResources().getDrawable(R.drawable.ic_misc))
                .setContent(mTCF));
    }

From source file:eu.trentorise.smartcampus.launcher.AppFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    AboutFragment newFragment;/*from  w ww .  j a v  a  2  s .  co  m*/
    Bundle args;
    FragmentTransaction transaction;
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.settings:
        startActivity(new Intent(getSherlockActivity(), SettingsActivity.class));
        return true;
    case R.id.about:
        // Intent browserIntent = new Intent(Intent.ACTION_VIEW,
        // Uri.parse(getString(R.string.smartcampus_url_credits)));
        // startActivity(browserIntent);
        newFragment = new AboutFragment();
        args = new Bundle();
        newFragment.setArguments(args);
        transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.addToBackStack(null);
        transaction.commit();
        return true;
    case R.id.help:
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //         TextView tv = new TextView(getActivity());
        //         tv.setPadding(20, 20, 20, 20);
        //         tv.setTextSize(18f);
        //         tv.setText(Html.fromHtml(getString(R.string.about_2)));
        WebView wv = new WebView(getActivity());
        wv.loadData(getString(R.string.about_2), "text/html; charset=UTF-8", "utf-8");
        //tv.setMovementMethod(LinkMovementMethod.getInstance());
        builder.setTitle(android.R.string.dialog_alert_title).setView(wv).create().show();
        return true;
    default:
        return super.onOptionsItemSelected(item);

    }

}

From source file:dev.memento.MainActivity.java

private void initUI() {

    mDateChosenButton = (Button) findViewById(R.id.dateChosen);
    mDateDisplayedView = (TextView) findViewById(R.id.dateDisplayed);
    mNowButton = (Button) findViewById(R.id.nowButton);
    mNowButton.setEnabled(false);//from  w w  w. jav a 2s . co m

    mPageLoadingProgressBar = (ProgressBar) findViewById(R.id.pageLoadProgressBar);
    mPageLoadingProgressBar.setVisibility(View.GONE);

    mMementoProgressBar = (ProgressBar) findViewById(R.id.loadMementosProgressBar);
    mMementoProgressBar.setVisibility(View.GONE);

    mLocation = (AutoCompleteTextView) findViewById(R.id.locationEditText);

    // Load list of popular URLs so they are easier to enter 
    String[] defaultSites = getResources().getStringArray(R.array.defaultWebsites);
    if (mLocationAdapter == null)
        mLocationAdapter = new LocationAutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line,
                defaultSites);

    mLocation.setAdapter(mLocationAdapter);
    mLocation.setFocusableInTouchMode(true);
    mLocation.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            // Go to URL if user presses enter
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {

                String url = Utilities.fixUrl(mLocation.getText().toString());
                if (Utilities.isArchiveUrl(url)) {
                    // Don't do anything but load the URL
                    if (Log.LOG)
                        Log.d(LOG_TAG, "Loading archive URL " + url);
                } else if (Utilities.isValidUrl(url)) {
                    // Always bounce to the present when the user types a URL

                    mOriginalUrl = url;
                    if (Log.LOG)
                        Log.d(LOG_TAG, "Browsing to NOW " + url);

                    mLocationAdapter.add(url);
                    resetMementoButtons();
                    mCurrentMemento = null;

                    // Clear since we are visiting a different page in the present
                    mMementos.clear();

                    surfToUrl(mOriginalUrl);

                    // Hide the virtual keyboard
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(mLocation.getWindowToken(), 0);

                    mWebview.requestFocus();

                    return true;
                } else {
                    MainActivity.this.showToast("Please enter a valid URL.");

                    // Put focus back in text box
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mLocation.requestFocus();

                            // Select all text
                            mLocation.setSelection(0, mLocation.getText().length());
                        }
                    }, 200);

                    return true;
                }
            }

            return false;
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next);
    setImageButtonEnabled(false, mNextButton, R.drawable.next_item);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Advance to next Memento
            Memento nextMemento = null;

            // This could happen if the index has not been set yet
            if (mMementos.getCurrentIndex() < 0) {
                int index = mMementos.getIndexByDate(mDateDisplayed);
                if (index < 0) {
                    if (Log.LOG)
                        Log.d(LOG_TAG, "Could not find Memento with date " + mDateDisplayed + " ("
                                + mMementos.size() + " mementos). Try to find next another way.");

                    // Try alternative way of getting the next memento
                    nextMemento = mMementos.getNext(mDateDisplayed);
                } else {
                    mMementos.setCurrentIndex(index);
                    nextMemento = mMementos.getNext();
                }
            } else {
                // Locate the next Memento in the list
                nextMemento = mMementos.getNext();
            }

            if (nextMemento == null) {
                // This could happen if we got redirected to the memento and didn't know
                // it was the last memento, so the Next button was not disabled
                if (Log.LOG)
                    Log.d(LOG_TAG, "Still could not find next Memento.");
                if (Log.LOG)
                    Log.d(LOG_TAG, "Current index is " + mMementos.getCurrentIndex());
                setImageButtonEnabled(false, mNextButton, R.drawable.next_item);
            } else {
                SimpleDateTime date = nextMemento.getDateTime();
                //setChosenDate(nextMemento.getDateTime());
                showToast("Time traveling to next Memento on " + date.dateFormatted());
                if (Log.LOG)
                    Log.d(LOG_TAG, "Going to next Memento on " + date);

                mDateDisplayed = date;

                mCurrentMemento = nextMemento;
                String redirectUrl = nextMemento.getUrl();
                surfToUrl(redirectUrl);

                // Just in case it wasn't already enabled
                //mPreviousButton.setEnabled(true);
                MainActivity.this.setImageButtonEnabled(true, mPreviousButton, R.drawable.previous_item);

                // If this is the last memento, disable button
                if (mMementos.isLast(date))
                    setImageButtonEnabled(false, mNextButton, R.drawable.next_item);
            }
        }
    });

    mPreviousButton = (ImageButton) findViewById(R.id.previous);
    setImageButtonEnabled(false, mPreviousButton, R.drawable.previous_item);
    mPreviousButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Advance to previous Memento
            Memento prevMemento = null;

            // This could happen if the index has not been set yet
            if (mMementos.getCurrentIndex() < 0) {
                int index = mMementos.getIndexByDate(mDateDisplayed);
                if (index < 0) {
                    if (Log.LOG)
                        Log.d(LOG_TAG, "Could not find Memento with date " + mDateDisplayed + " ("
                                + mMementos.size() + " mementos). Try to find previous" + " another way.");

                    // Try alternative way of getting the pervious memento
                    prevMemento = mMementos.getPrevious(mDateDisplayed);
                } else {
                    mMementos.setCurrentIndex(index);
                    prevMemento = mMementos.getPrevious();
                }
            } else {
                // Locate the prev Memento in the list
                prevMemento = mMementos.getPrevious();
            }

            if (prevMemento == null) {
                if (Log.LOG)
                    Log.d(LOG_TAG, "Still could not find previous Memento!");
                if (Log.LOG)
                    Log.d(LOG_TAG, "Current index is " + mMementos.getCurrentIndex());
                setImageButtonEnabled(false, mPreviousButton, R.drawable.previous_item);
            } else {
                SimpleDateTime date = prevMemento.getDateTime();

                showToast("Time traveling to previous Memento on " + date.dateFormatted());
                if (Log.LOG)
                    Log.d(LOG_TAG, "Going to previous Memento on " + date);

                mDateDisplayed = date;

                mCurrentMemento = prevMemento;
                String redirectUrl = prevMemento.getUrl();
                surfToUrl(redirectUrl);

                // Just in case it wasn't already enabled
                setImageButtonEnabled(true, mNextButton, R.drawable.next_item);

                // If this is the first memento, disable button
                if (mMementos.isFirst(date))
                    setImageButtonEnabled(false, mPreviousButton, R.drawable.previous_item);
            }
        }
    });

    // Idea to use placeholder and handle orientation changes ourself is from here:
    // http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/
    webViewPlaceholder = ((FrameLayout) findViewById(R.id.webViewPlaceholder));
    if (mWebview == null) {
        mWebview = new WebView(this);
        mWebview.setLayoutParams(
                new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mWebview.getSettings().setSupportZoom(true);
        mWebview.getSettings().setBuiltInZoomControls(true);
        mWebview.getSettings().setLoadWithOverviewMode(true);

        // Setting to true allows the zoom-in to work, but problems moving around.
        // Sometimes the underlying webview library also set faults and crashes the app
        // http://stackoverflow.com/questions/17187338/android-fatal-signal-11-sigsegv-in-webviewcorethre
        // Safer to leave off although zoom won't work. 
        //mWebview.getSettings().setUseWideViewPort(true);

        mWebview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebview.setScrollbarFadingEnabled(true);
        mWebview.getSettings().setLoadsImagesAutomatically(true);
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.setWebViewClient(new MementoWebViewClient());
        mWebview.setWebChromeClient(new MementoWebChromClient());
        mWebview.getSettings().setUserAgentString(mUserAgent);

        // Must be declared before favicons will be received
        // http://stackoverflow.com/questions/3462582/display-the-android-webviews-favicon           
        WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());

        surfToUrl(mCurrentUrl);

        // Get focus away from location field
        mWebview.requestFocus();
    }

    webViewPlaceholder.addView(mWebview);

    mWebview.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            // Hide the virtual keyboard
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(mLocation.getWindowToken(), 0);

            return false;
        }
    });
}

From source file:net.robotmedia.acv.ui.widget.OcrLayout.java

/** Initialization routine called by the constructor. */
private void init(Context context) {
    // Exit if in the Eclipse graphical editor
    if (this.isInEditMode()) {
        return;//from  w  ww  .j  a  v a  2  s  . c o m
    }

    this.context = context;

    this.readOcrSettings(context);

    this.determineScreenDimensions(context);

    File externalDir = this.context.getExternalFilesDir(null);
    this.tesseractDbDir = new File(externalDir.toString() + Constants.TESSERACT_ROOT_DIR);
    this.tesseractDbFile = new File(externalDir.toString() + Constants.TESSDATA_DIR,
            Constants.TESSERACT_DB_FILENAME);
    this.edictDbFile = new File(externalDir, Constants.EDICT_DB_FILENAME);
    this.namesDbFile = new File(externalDir, Constants.NAMES_DB_FILENAME);
    this.kanjiDbFile = new File(externalDir, Constants.KANJI_DB_FILENAME);
    this.kanjiDefFormatFile = new File(externalDir, Constants.KANJI_DEF_FORMAT_FILENAME);
    this.deinflectionDbFile = new File(externalDir, Constants.DEINFLECTION_DB_FILENAME);
    this.substitutionsDbFile = new File(externalDir, Constants.SUBSTITUTIONS_DB_FILENAME);
    this.freqDbFile = new File(externalDir, Constants.FREQ_DB_FILENAME);

    this.wordSetKnown = new WordSet(new File(externalDir, Constants.KNOWN_WORDS_FILENAME));
    this.wordSetTodo = new WordSet(new File(externalDir, Constants.TODO_WORDS_FILENAME));

    // Add OCR view
    this.ocrView = new OcrView(context);
    this.addView(this.ocrView);

    // Add dictionary view
    this.dicView = new WebView(context);
    this.dicView.setBackgroundColor(this.ocrSettingsDictBackgroundColor); // Make the background translucent.
    this.dicView.loadDataWithBaseURL(null, "<html><body></body></html>", "text/html", "utf-8", null);
    this.dicView.setVisibility(GONE);
    this.addView(this.dicView);

    // Set the path to eplkup
    ContextWrapper cw = new ContextWrapper(this.context);

    // Android 5.0 requires executables to be compiled with PIE (Position Independent Executable) support for security
    // reasons. However, PIE is not supported before Android 4.1, which is why we have 2 executables, one with
    // PIE and one without PIE.
    if (android.os.Build.VERSION.SDK_INT >= 20) {
        DicEpwing.setEplkupExe(cw.getApplicationInfo().dataDir + "/" + Constants.EPLKUP_FILENAME);
    } else {
        DicEpwing.setEplkupExe(cw.getApplicationInfo().dataDir + "/" + Constants.EPLKUP_NON_PIE_FILENAME);
    }
}

From source file:ir.actfun.toofan.activities.MainActivity.java

private void aboutDialog() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Toofan");
    alert.setIcon(R.mipmap.ic_launcher);
    final WebView webView = new WebView(this);
    String about = "<p>A lightweight, Materialized and Precise weather app.</p>"
            + "<p>Developed by <a href='mailto:aligholami7596@gmail.com'>Ali Gholami</a></p>"
            + "Graphical Design and Support by <a href='http://www.mtabatabaei.com/'>Mohamad Tabatabaei</a></p>"
            + "co-developers: <a href='mailto:khajavi_mohamad@yahoo.com'>Mohamad Khajavi</a></p>  <a href='mailto:faezehsalmanfar@gmail.com'>Faezeh Salmanfar</a></p>"
            + "<p>Data provided by <a href='http://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>"
            + "<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
    if (darkTheme) {
        // Style text color for dark theme
        about = "<style media=\"screen\" type=\"text/css\">" + "body {\n" + "    color:white;\n" + "}\n"
                + "a:link {color:cyan}\n" + "</style>" + about;
    }//w  w w  .  j  a  v  a2s .co m
    webView.setBackgroundColor(Color.TRANSPARENT);
    webView.loadData(about, "text/html", "UTF-8");
    alert.setView(webView, 32, 0, 32, 0);
    alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

        }
    });
    alert.show();
}