Example usage for android.view Gravity CENTER_VERTICAL

List of usage examples for android.view Gravity CENTER_VERTICAL

Introduction

In this page you can find the example usage for android.view Gravity CENTER_VERTICAL.

Prototype

int CENTER_VERTICAL

To view the source code for android.view Gravity CENTER_VERTICAL.

Click Source Link

Document

Place object in the vertical center of its container, not changing its size.

Usage

From source file:org.apache.cordova.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from  w w  w.ja va 2  s.  co m*/
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // 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) {
                    closeDialog();
                }
            });

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

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_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
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setText("<");
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setText(">");
            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.MATCH_PARENT, LayoutParams.MATCH_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
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setText(buttonLabel);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.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(inAppWebView);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:org.telegram.ui.ActionBar.ActionBarMenuItem.java

public ActionBarMenuItem setIsSearchField(boolean value) {
    if (parentMenu == null) {
        return this;
    }//w  ww .  j a  v  a  2s .  c  o  m
    if (value && searchContainer == null) {
        searchContainer = new FrameLayout(getContext());
        parentMenu.addView(searchContainer, 0);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) searchContainer.getLayoutParams();
        layoutParams.weight = 1;
        layoutParams.width = 0;
        layoutParams.height = LayoutHelper.MATCH_PARENT;
        layoutParams.leftMargin = AndroidUtilities.dp(6);
        searchContainer.setLayoutParams(layoutParams);
        searchContainer.setVisibility(GONE);

        searchField = new EditText(getContext());
        searchField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        searchField.setHintTextColor(0x88ffffff);
        searchField.setTextColor(0xffffffff);
        searchField.setSingleLine(true);
        searchField.setBackgroundResource(0);
        searchField.setPadding(0, 0, 0, 0);
        int inputType = searchField.getInputType() | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
        searchField.setInputType(inputType);
        searchField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {

            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });
        searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (/*actionId == EditorInfo.IME_ACTION_SEARCH || */event != null
                        && (event.getAction() == KeyEvent.ACTION_UP
                                && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH
                                || event.getAction() == KeyEvent.ACTION_DOWN
                                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    AndroidUtilities.hideKeyboard(searchField);
                    if (listener != null) {
                        listener.onSearchPressed(searchField);
                    }
                }
                return false;
            }
        });
        searchField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (listener != null) {
                    listener.onTextChanged(searchField);
                }
                if (clearButton != null) {
                    clearButton.setAlpha(s == null || s.length() == 0 ? 0.6f : 1.0f);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        try {
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchField, R.drawable.search_carret);
        } catch (Exception e) {
            //nothing to do
        }
        searchField.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_SEARCH);
        searchField.setTextIsSelectable(false);
        searchContainer.addView(searchField);
        FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) searchField.getLayoutParams();
        layoutParams2.width = LayoutHelper.MATCH_PARENT;
        layoutParams2.gravity = Gravity.CENTER_VERTICAL;
        layoutParams2.height = AndroidUtilities.dp(36);
        layoutParams2.rightMargin = AndroidUtilities.dp(48);
        searchField.setLayoutParams(layoutParams2);

        clearButton = new ImageView(getContext());
        clearButton.setImageResource(R.drawable.ic_close_white);
        clearButton.setScaleType(ImageView.ScaleType.CENTER);
        clearButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                searchField.setText("");
                searchField.requestFocus();
                AndroidUtilities.showKeyboard(searchField);
            }
        });
        searchContainer.addView(clearButton);
        layoutParams2 = (FrameLayout.LayoutParams) clearButton.getLayoutParams();
        layoutParams2.width = AndroidUtilities.dp(48);
        layoutParams2.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        layoutParams2.height = LayoutHelper.MATCH_PARENT;
        clearButton.setLayoutParams(layoutParams2);
    }
    isSearchField = value;
    return this;
}

From source file:org.openhab.habdroid.ui.OpenHABMainActivity.java

private void setupToolbar() {
    mToolbar = (Toolbar) findViewById(R.id.openhab_toolbar);
    setSupportActionBar(mToolbar);/*from  w  ww  .  ja  va2 s.co  m*/
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    // ProgressBar layout params inside the toolbar have to be done programmatically
    // because it doesn't work through layout file :-(
    mProgressBar = (ProgressBar) mToolbar.findViewById(R.id.toolbar_progress_bar);
    mProgressBar.setLayoutParams(new Toolbar.LayoutParams(Gravity.END | Gravity.CENTER_VERTICAL));
    setProgressIndicatorVisible(true);
}

From source file:com.oonhee.oojs.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from  w  w w  . j  a va2 s  .  com
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // 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) {
                    closeDialog();
                }
            });

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

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_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
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setText("<");
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setText(">");
            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.MATCH_PARENT, LayoutParams.MATCH_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
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setText(buttonLabel);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new AmazonWebView(cordova.getActivity());

            CordovaActivity app = (CordovaActivity) cordova.getActivity();
            cordova.getFactory().initializeWebView(inAppWebView, 0x00FF00, false, null);

            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            AmazonWebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            AmazonWebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(com.amazon.android.webkit.AmazonWebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                AmazonCookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                AmazonCookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.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(inAppWebView);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:widgets.Graphical_Info_with_achartengine.java

private void drawgraph() throws JSONException {
    minf = 0;//from   w w w .ja  v a2 s  .c o  m
    maxf = 0;
    avgf = 0;
    //Clear to avoid crash on multiple redraw
    EmptySeries.clear();
    nameSeries.clear();
    dataset.clear();
    //Clear all labels
    multiRenderer.clearXTextLabels();
    multiRenderer.clearYTextLabels();
    multiRenderer.removeAllRenderers();
    //Set position of graph to 0
    multiRenderer.setXAxisMin(0);
    //Adding nameSeries Series to the dataset
    dataset.addSeries(nameSeries);
    dataset.addSeries(EmptySeries);
    //Adding incomeRenderer and emptyRenderer to multipleRenderer
    //Note: The order of adding dataseries to dataset and renderers to multipleRenderer
    //should be same
    multiRenderer.addSeriesRenderer(incomeRenderer);
    multiRenderer.addSeriesRenderer(emptyRenderer);

    values = new Vector<Vector<Float>>();
    chartContainer = new LinearLayout(context);
    // Getting a reference to LinearLayout of the MainActivity Layout
    chartContainer
            .setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    chartContainer.setGravity(Gravity.CENTER_VERTICAL);
    chartContainer.setPadding((int) size5, (int) size10, (int) size5, (int) size10);

    currentTimestamp = time_end.getTime() / 1000;
    startTimestamp = time_start.getTime() / 1000;

    //Tracer.i(mytag,"UpdateThread ("+dev_id+") : "+url+"stats/"+dev_id+"/"+state_key+"/from/"+startTimestamp+"/to/"+currentTimestamp+"/interval/"+step+"/selector/avg");
    Tracer.i(mytag, "UpdateThread (" + dev_id + ") : " + url + "stats/" + dev_id + "/" + state_key + "/from/"
            + startTimestamp + "/to/" + currentTimestamp + "/interval/" + step + "/selector/avg");
    JSONObject json_GraphValues = null;
    try {
        //json_GraphValues = Rest_com.connect(url+"stats/"+dev_id+"/"+state_key+"/from/"+startTimestamp+"/to/"+1385857510+"/interval/"+step+"/selector/avg");
        json_GraphValues = Rest_com.connect(url + "stats/" + dev_id + "/" + state_key + "/from/"
                + startTimestamp + "/to/" + currentTimestamp + "/interval/" + step + "/selector/avg", login,
                password);

    } catch (Exception e) {
        //return null;
        Tracer.e(mytag, "Error with json");
    }
    JSONArray itemArray = json_GraphValues.getJSONArray("stats");
    JSONArray valueArray = itemArray.getJSONObject(0).getJSONArray("values");
    j = 0;
    Boolean ruptur = false;
    for (int i = 0; i < valueArray.length() - 1; i++) {
        real_val = valueArray.getJSONArray(i).getDouble(limit - 1);
        real_val = round(real_val, 2);
        int year = valueArray.getJSONArray(i).getInt(0);
        int month = valueArray.getJSONArray(i).getInt(1);
        int week = valueArray.getJSONArray(i).getInt(2);
        int day = valueArray.getJSONArray(i).getInt(3);
        int hour = valueArray.getJSONArray(i).getInt(4);
        int hour_next = valueArray.getJSONArray(i + 1).getInt(4);
        String date = String.valueOf(hour) + "'";
        if (hour != 23 && (hour < hour_next)) {
            //no day change
            if ((hour + 1) != hour_next) {
                //ruptur : simulate next missing steps
                EmptySeries.add(j, real_val);
                nameSeries.add(j, real_val);
                multiRenderer.addXTextLabel(j, date);
                Tracer.d(mytag, "Ok " + j + " hour: " + hour + " value: " + real_val);
                for (int k = 1; k < (hour_next - hour); k++) {
                    nameSeries.add(j + k, MathHelper.NULL_VALUE);
                    EmptySeries.add(j + k, real_val);
                    Tracer.d(mytag, "Missing " + (j + k) + " hour: " + (hour + k) + " value: " + real_val);
                }
                j = j + (hour_next - hour);
                ruptur = true;
            } else {
                if (ruptur) {
                    EmptySeries.add(j, real_val);
                } else {
                    EmptySeries.add(j, MathHelper.NULL_VALUE);
                }
                ruptur = false;
                nameSeries.add(j, real_val); //change to j to avoid missing value
                //EmptySeries.add(j+1,real_val );
                multiRenderer.addXTextLabel(j, date);
                Tracer.d(mytag, "Ok " + j + " hour: " + hour + " value: " + real_val);
                j++;
            }
        } else if (hour == 23) {
            if (ruptur) {
                EmptySeries.add(j, real_val);
            } else {
                EmptySeries.add(j, MathHelper.NULL_VALUE);
            }
            ruptur = false;
            nameSeries.add(j, real_val); //change to j to avoid missing value
            multiRenderer.addXTextLabel(j, date);
            Tracer.d(mytag, "Ok " + j + " value for 23h: " + real_val);
            j++;
        }
        if (minf == 0)
            minf = real_val.floatValue();
        avgf += real_val; // Get the real 'value'

        if (real_val > maxf) {
            maxf = real_val.floatValue();

        }
        if (real_val < minf) {
            minf = real_val.floatValue();

        }
    }
    avgf = avgf / values.size();
    multiRenderer.addYTextLabel(((double) minf) - 1, ("" + minf));
    multiRenderer.addYTextLabel(((double) avgf), ("" + avgf));
    multiRenderer.addYTextLabel(((double) maxf), ("" + maxf));
    //SET limit up and down on Y axis
    multiRenderer.setYAxisMin(minf - 1);
    multiRenderer.setYAxisMax(maxf + 1);
    Tracer.d(mytag, "minf (" + dev_id + ")=" + minf);
    Tracer.d(mytag, "maxf (" + dev_id + ")=" + maxf);
    Tracer.d(mytag, "avgf (" + dev_id + ")=" + avgf);
    Tracer.d(mytag, "UpdateThread (" + dev_id + ") Refreshing graph");

    // Specifying chart types to be drawn in the graph
    // Number of data series and number of types should be same
    // Order of data series and chart type will be same
    String[] types = new String[] { LineChart.TYPE, LineChart.TYPE };
    // Creating a combined chart with the chart types specified in types array
    mChart = (GraphicalView) ChartFactory.getCombinedXYChartView(context, dataset, multiRenderer, types);

    mChart.addPanListener(new PanListener() {
        public void panApplied() {
            Tracer.i(mytag + "Pan",
                    "New X range=[" + multiRenderer.getXAxisMin() + ", " + multiRenderer.getXAxisMax() + "]");
            //TO move the graph to left or right
            if (multiRenderer.getXAxisMin() < -2) {
                period_type = -1;
                compute_period();
                try {
                    mChart.destroyDrawingCache();
                    drawgraph();
                } catch (JSONException e) {
                    Tracer.d(mytag, e.toString());
                }
            }
            if (multiRenderer.getXAxisMax() > j + 2) {
                period_type = 0;
                compute_period();
                try {
                    mChart.destroyDrawingCache();
                    drawgraph();
                } catch (JSONException e) {
                    Tracer.d(mytag, e.toString());
                }
            }
        }
    });

    // Adding the Combined Chart to the LinearLayout
    chartContainer.addView(mChart);
}

From source file:de.mrapp.android.preference.AbstractColorPickerPreference.java

/**
 * Creates and returns the layout params of the view, which is used to show a preview of the
 * preference's color, depending on the preference's properties.
 *
 * @return The layout params, which have been created, as an instance of the class {@link
 * LayoutParams}/*from w w  w  .j  av  a2 s.c  om*/
 */
private LayoutParams createPreviewLayoutParams() {
    LayoutParams layoutParams = new LayoutParams(getPreviewSize(), getPreviewSize());
    layoutParams.gravity = Gravity.CENTER_VERTICAL;
    return layoutParams;
}

From source file:com.adarshahd.indianrailinfo.donate.PNRStat.java

private void createTableLayoutTrnDtls() {
    if (mPageResult.contains("FLUSHED PNR / ") || mPageResult.contains("Invalid PNR")) {
        mTextViewPNRSts.setText("The PNR entered is either invalid or expired! Please check.");
        mFrameLayout.removeAllViews();//from www  . j  ava 2s.  c om
        mFrameLayout.addView(mTextViewPNRSts);
        return;
    }
    if (mPageResult.contains("Connectivity Failure") || mPageResult.contains("try again")) {
        mTextViewPNRSts.setText("Looks like server is busy or currently unavailable. Please try again later!");
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(mTextViewPNRSts);
        return;
    }
    List<String> trainList;
    if (mTrainDetails == null || mTrainDetails.getPNR() != mPNRNumber) {
        Elements eleTrain = Jsoup.parse(mPageResult).select("table tr tr td:containsOwn(Train Number)");
        Iterator iteTrain = null;
        try {
            iteTrain = eleTrain.first().parent().parent().parent().getElementsByTag("tr").iterator();
        } catch (Exception e) {
            Log.i("PNRStat", mPageResult);
            return;
        }
        trainList = new ArrayList<String>();
        Element tmp;
        //Get the third row for train details
        iteTrain.next();
        iteTrain.next();
        if (iteTrain.hasNext()) {
            tmp = (Element) iteTrain.next();
            trainList.add(tmp.select("td").get(0).text());
            trainList.add(tmp.select("td").get(1).text());
            trainList.add(tmp.select("td").get(2).text());
            trainList.add(tmp.select("td").get(5).text());
            trainList.add(tmp.select("td").get(6).text());
            trainList.add(tmp.select("td").get(7).text());
        }
        mTrainDetails = new TrainDetails(trainList, mPNRNumber);
    } else {
        trainList = mTrainDetails.getTrainDetails();
    }
    mTableLayoutTrn = new TableLayout(mActivity);
    mTableLayoutTrn.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    TableRow row = new TableRow(mActivity);
    mStrTrainDetails = new String();
    row.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    for (String list : trainList) {
        TextView tv = new TextView(mActivity);
        tv.setText(list);
        tv.setPadding(10, 10, 10, 10);
        tv.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Small);
        row.addView(tv);
        mStrTrainDetails += list + " ";
    }
    row.setBackgroundResource(R.drawable.card_background);
    row.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    mTableLayoutTrn.addView(row);
}

From source file:com.actionbarsherlock.internal.view.menu.ActionMenuView.java

@Override
protected LayoutParams generateDefaultLayoutParams() {
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER_VERTICAL;
    return params;
}

From source file:com.adarshahd.indianrailinfo.donate.TrainDetails.java

private void createTableLayoutTrainFare() {
    if (mPage.contains("SORRY")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Not a valid class, Please select a different class and try again.");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();//from   w  w  w .  ja v  a  2  s  .  c  om
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }
    if (mPage.contains("ISL Of")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Station is not in ISL Of the Train. \nPlease modify the source/destination!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("ERROR")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Your request resulted in an error.\nPlease check!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("Network Connectivity")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText("Looks like the server is busy.\nPlease try later!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mPage.contains("unavailable")) {
        TextView textViewTrnDtls = new TextView(mActivity);
        textViewTrnDtls.setText(
                "Response from server:\n\nYour request could not be processed now. \nPlease try again later!");
        textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
        textViewTrnDtls.setPadding(10, 10, 10, 10);
        textViewTrnDtls.setTextColor(Color.RED);
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(textViewTrnDtls);
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
        return;
    }

    if (mDetails == null || !mDetails.getTrainNumber().equals(mTrainNumber)) {
        Iterator iterator = null;
        try {
            iterator = mElements.first().parent().parent().parent().getElementsByTag("tr").iterator();
        } catch (Exception e) {
            Log.i("TrainDetails", mPage);
        }
        mListFr = new ArrayList<List<String>>();
        List<String> list;
        Element tmp;
        while (iterator.hasNext()) {
            tmp = (Element) iterator.next();
            list = new ArrayList<String>();
            list.add(tmp.select("td").get(0).text());
            list.add(tmp.select("td").get(1).text());
            mListFr.add(list);
        }
        mDetails = new Details(mListFr, TrainEnquiry.FARE, mTrainNumber);
    } else {
        mListFr = mDetails.getList();
    }
    mTblLayoutFr = new TableLayout(mActivity);
    TableRow row;
    TextView tv1, tv2;
    mTblLayoutFr.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    for (int i = 0; i < mListFr.size(); i++) {
        row = new TableRow(mActivity);
        tv1 = new TextView(mActivity);
        tv2 = new TextView(mActivity);

        tv1.setText("   " + mListFr.get(i).get(0));
        tv2.setText("   " + mListFr.get(i).get(1));

        tv1.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);
        tv2.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);

        tv1.setPadding(5, 5, 5, 5);
        tv2.setPadding(5, 5, 5, 5);

        /*tv2.setBackgroundResource(R.drawable.card_divider);
        tv3.setBackgroundResource(R.drawable.card_divider);
        tv4.setBackgroundResource(R.drawable.card_divider);*/

        row.addView(tv1);
        row.addView(tv2);

        row.setBackgroundResource(R.drawable.button_selector);
        row.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
        mTblLayoutFr.addView(row);
    }
    LinearLayout ll = new LinearLayout(mActivity);
    ScrollView scrollView = new ScrollView(mActivity);
    TextView textViewTrnDtls = new TextView(mActivity);
    textViewTrnDtls.setText("Fare details:");
    textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    textViewTrnDtls.setPadding(10, 10, 10, 10);
    ll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(textViewTrnDtls);
    ll.addView(mTblLayoutFr);
    scrollView.addView(ll);
    mFrameLayout.removeAllViews();
    mFrameLayout.addView(scrollView);
    if (mDialog.isShowing()) {
        mDialog.cancel();
    }
}

From source file:com.egloos.hyunyi.musicinfo.LinkPopUp.java

private void displayArtistInfo(JSONObject j) throws JSONException {
    if (imageLoader == null)
        imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited())
        imageLoader.init(config);// ww w . ja v a 2 s  . c om

    Log.i("musicInfo", "LinkPopUp. displayArtistInfo " + j.toString());

    //JSONObject j_artist_info = j.getJSONObject("artist");

    final String artist_name = j.getString("name");

    tArtistName.setText(artist_name);
    final JSONObject urls = j.optJSONObject("urls");
    final JSONArray videos = j.optJSONArray("video");
    final JSONArray images = j.optJSONArray("images");

    final String msg = artist_name.replaceAll("\\p{Punct}", " ").replaceAll("\\p{Space}", "+");

    AsyncHttpClient client = new AsyncHttpClient();

    String fmURL = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + msg
            + "&autocorrect[1]&format=json&api_key=ca4c10f9ae187ebb889b33ba12da7ee9";
    Log.i("musicInfo", fmURL);

    client.get(fmURL, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String r = new String(responseBody);
            ArrayList<String> image_urls = new ArrayList<String>();

            try {
                Log.i("musicInfo", "Communicating with LastFM...");

                JSONObject json = new JSONObject(r);
                Log.i("musicInfo", json.toString());

                json = json.getJSONObject("artist");
                Log.i("musicInfo", json.toString());

                JSONArray artist_images = json.optJSONArray("image");
                Log.i("musicInfo", artist_images.toString());

                for (int i = 0; i < artist_images.length(); i++) {
                    JSONObject j = artist_images.getJSONObject(i);
                    Log.i("musicInfo", j.optString("size"));
                    if (j.optString("size").contains("extralarge")) {
                        image_urls.add(j.optString("#text"));
                        //b.putString("fm_image", j.getString("#text"));
                        //Log.i("musicInfo", j.getString("#text"));
                        break;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (images != null) {
                for (int i = 0; i < images.length(); i++) {
                    JSONObject image = null;
                    try {
                        image = images.getJSONObject(i);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    int width = image.optInt("width", 0);
                    int height = image.optInt("height", 0);
                    String url = image.optString("url", "");
                    Log.i("musicInfo", i + ": " + url);
                    if ((width * height > 10000) && (width * height < 100000)
                            && (!url.contains("userserve-ak"))) {
                        //if ((width>300&&width<100)&&(height>300&&height<1000)&&(!url.contains("userserve-ak"))) {
                        image_urls.add(url);
                        Log.i("musicInfo", "Selected: " + url);
                        //available_images.put(image);
                    }
                }
            }

            int random = (int) (Math.random() * image_urls.size());
            final String f_url = image_urls.get(random);

            Log.i("musicInfo",
                    "Total image#=" + image_urls.size() + " Selected image#=" + random + " " + f_url);

            if (image_urls.size() > 0) {
                imageLoader.displayImage(f_url, ArtistImage, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        lLinkList.removeAllViews();
                        //String attr = fImage.optJSONObject("license").optString("attribution");
                        //tAttribution.setText("Credit. " + ((attr == null) || (attr.contains("n/a")) ? "Unknown" : attr));
                        if (urls != null) {
                            String[] jsonName = { "wikipedia_url", "mb_url", "lastfm_url", "official_url",
                                    "twitter_url" };
                            for (int i = 0; i < jsonName.length; i++) {
                                if ((urls.optString(jsonName[i]) != null)
                                        && (urls.optString(jsonName[i]) != "")) {
                                    Log.d("musicinfo", "Link URL: " + urls.optString(jsonName[i]));
                                    TextView tv = new TextView(getApplicationContext());
                                    tv.setTextSize(11);
                                    tv.setPadding(16, 16, 16, 16);
                                    tv.setTextColor(Color.LTGRAY);
                                    tv.setTypeface(Typeface.SANS_SERIF);
                                    tv.setGravity(Gravity.CENTER_VERTICAL);

                                    switch (jsonName[i]) {
                                    case "official_url":
                                        tv.setText("HOME.");
                                        break;
                                    case "wikipedia_url":
                                        tv.setText("WIKI.");
                                        break;
                                    case "mb_url":
                                        tv.setText("Music Brainz.");
                                        break;
                                    case "lastfm_url":
                                        tv.setText("Last FM.");
                                        break;
                                    case "twitter_url":
                                        tv.setText("Twitter.");
                                        break;
                                    }

                                    try {
                                        tv.setTag(urls.getString(jsonName[i]));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    tv.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent = new Intent();
                                            intent.setAction(Intent.ACTION_VIEW);
                                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                                            intent.setData(Uri.parse((String) v.getTag()));
                                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            startActivity(intent);
                                            Toast.makeText(getApplicationContext(), "Open the Link...",
                                                    Toast.LENGTH_SHORT).show();
                                            //finish();
                                        }
                                    });
                                    lLinkList.addView(tv);
                                }
                            }
                        } else {
                            TextView tv = new TextView(getApplicationContext());
                            tv.setTextSize(11);
                            tv.setPadding(16, 16, 16, 16);
                            tv.setTextColor(Color.LTGRAY);
                            tv.setTypeface(Typeface.SANS_SERIF);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            tv.setText("Sorry, No Link Here...");
                            lLinkList.addView(tv);
                        }

                        if (videos != null) {
                            jVideoArray = videos;
                            mAdapter = new StaggeredViewAdapter(getApplicationContext(),
                                    android.R.layout.simple_list_item_1, generateImageData(videos));
                            //if (mData == null) {
                            mData = generateImageData(videos);
                            //}

                            //mAdapter.clear();

                            for (JSONObject data : mData) {
                                mAdapter.add(data);
                            }
                            mGridView.setAdapter(mAdapter);
                        } else {

                        }

                        adjBottomColor(((ImageView) view).getDrawable());
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {

                    }
                });
            } else {
                ArtistImage.setImageResource(R.drawable.lamb_no_image_available);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}