Example usage for android.widget LinearLayout setOrientation

List of usage examples for android.widget LinearLayout setOrientation

Introduction

In this page you can find the example usage for android.widget LinearLayout setOrientation.

Prototype

public void setOrientation(@OrientationMode int orientation) 

Source Link

Document

Should the layout be a column or a row.

Usage

From source file:com.grarak.kerneladiutor.fragments.other.SettingsFragment.java

private void deletePasswordDialog(final String password) {
    if (password.isEmpty()) {
        Utils.toast(getString(R.string.set_password_first), getActivity());
        return;//from w w w . jav a2  s  . c  o m
    }

    mDeletePassword = password;

    LinearLayout linearLayout = new LinearLayout(getActivity());
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setGravity(Gravity.CENTER);
    int padding = Math.round(getResources().getDimension(R.dimen.dialog_padding));
    linearLayout.setPadding(padding, padding, padding, padding);

    final AppCompatEditText mPassword = new AppCompatEditText(getActivity());
    mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    mPassword.setHint(getString(R.string.password));
    linearLayout.addView(mPassword);

    new Dialog(getActivity()).setView(linearLayout)
            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (!mPassword.getText().toString().equals(Utils.decodeString(password))) {
                        Utils.toast(getString(R.string.password_wrong), getActivity());
                        return;
                    }

                    Prefs.saveString("password", "", getActivity());
                    if (mFingerprint != null) {
                        mFingerprint.setEnabled(false);
                    }
                }
            }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    mDeletePassword = null;
                }
            }).show();
}

From source file:fr.cph.chicago.core.adapter.NearbyAdapter.java

private View handleBikes(final int position, @NonNull final ViewGroup parent) {
    final LayoutInflater vi = (LayoutInflater) parent.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View convertView = vi.inflate(R.layout.list_nearby, parent, false);

    final int index = position - (stations.size() + busStops.size());
    final BikeStation bikeStation = bikeStations.get(index);

    final LinearLayout favoritesData = (LinearLayout) convertView.findViewById(R.id.nearby_results);

    final ImageView imageView = (ImageView) convertView.findViewById(R.id.icon);
    imageView.setImageDrawable(/*  w w  w .j ava2s .co m*/
            ContextCompat.getDrawable(parent.getContext(), R.drawable.ic_directions_bike_white_24dp));

    final TextView routeView = (TextView) convertView.findViewById(R.id.station_name);
    routeView.setText(bikeStation.getName());

    final LinearLayout llh = new LinearLayout(context);
    llh.setOrientation(LinearLayout.HORIZONTAL);
    llh.setPadding(line1PaddingColor, stopsPaddingTop, 0, 0);

    final LinearLayout availableLayout = new LinearLayout(context);
    availableLayout.setOrientation(LinearLayout.VERTICAL);

    final LinearLayout.LayoutParams leftParam = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final RelativeLayout availableBikes = new RelativeLayout(context);
    availableBikes.setLayoutParams(leftParam);
    availableBikes.setPadding(line1PaddingColor, 0, 0, 0);

    final RelativeLayout lineIndication = LayoutUtil.createColoredRoundForFavorites(context, TrainLine.NA);
    int lineId = Util.generateViewId();
    lineIndication.setId(lineId);

    final RelativeLayout.LayoutParams availableParam = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    availableParam.addRule(RelativeLayout.RIGHT_OF, lineId);
    availableParam.setMargins(Util.convertDpToPixel(context, 10), 0, 0, 0);

    final TextView availableBike = new TextView(context);
    availableBike.setText(context.getString(R.string.bike_available_bikes));
    availableBike.setTextColor(ContextCompat.getColor(context, R.color.grey_5));
    availableBike.setLayoutParams(availableParam);
    int availableBikeId = Util.generateViewId();
    availableBike.setId(availableBikeId);

    final RelativeLayout.LayoutParams amountParam = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    amountParam.addRule(RelativeLayout.RIGHT_OF, availableBikeId);

    final TextView amountBike = new TextView(context);
    final String amountBikeText = String.valueOf(bikeStation.getAvailableBikes());
    amountBike.setText(amountBikeText);
    int color = bikeStation.getAvailableBikes() == 0 ? R.color.red : R.color.green;
    amountBike.setTextColor(ContextCompat.getColor(context, color));
    amountBike.setLayoutParams(amountParam);

    availableBikes.addView(lineIndication);
    availableBikes.addView(availableBike);
    availableBikes.addView(amountBike);

    final LinearLayout.LayoutParams leftParam2 = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final RelativeLayout availableDocks = new RelativeLayout(context);
    availableDocks.setLayoutParams(leftParam2);
    availableDocks.setPadding(line1PaddingColor, 0, 0, 0);

    final RelativeLayout lineIndication2 = LayoutUtil.createColoredRoundForFavorites(context, TrainLine.NA);
    int lineId2 = Util.generateViewId();
    lineIndication2.setId(lineId2);

    final RelativeLayout.LayoutParams availableDockParam = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    availableDockParam.addRule(RelativeLayout.RIGHT_OF, lineId2);
    availableDockParam.setMargins(Util.convertDpToPixel(context, 10), 0, 0, 0);

    final TextView availableDock = new TextView(context);
    availableDock.setText(context.getString(R.string.bike_available_docks));
    availableDock.setTextColor(ContextCompat.getColor(context, R.color.grey_5));
    availableDock.setLayoutParams(availableDockParam);
    int availableDockBikeId = Util.generateViewId();
    availableDock.setId(availableDockBikeId);

    final RelativeLayout.LayoutParams amountParam2 = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    amountParam2.addRule(RelativeLayout.RIGHT_OF, availableDockBikeId);

    final TextView amountDock = new TextView(context);
    final String amountDockText = String.valueOf(bikeStation.getAvailableDocks());
    amountDock.setText(amountDockText);
    color = bikeStation.getAvailableDocks() == 0 ? R.color.red : R.color.green;
    amountDock.setTextColor(ContextCompat.getColor(context, color));

    amountDock.setLayoutParams(amountParam2);

    availableDocks.addView(lineIndication2);
    availableDocks.addView(availableDock);
    availableDocks.addView(amountDock);

    availableLayout.addView(availableBikes);
    availableLayout.addView(availableDocks);

    llh.addView(availableLayout);

    favoritesData.addView(llh);

    convertView.setOnClickListener(new NearbyOnClickListener(googleMap, markers, bikeStation.getId(),
            bikeStation.getLatitude(), bikeStation.getLongitude()));
    return convertView;
}

From source file:org.vshgap.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, Context context) {
    super(context);
    SharedPreferences themePrefs = ApplicationLoader.applicationContext
            .getSharedPreferences(AndroidUtilities.THEME_PREFS, AndroidUtilities.THEME_PREFS_MODE);
    int bgColor = themePrefs.getInt("chatEmojiViewBGColor", 0xfff5f6f7);
    int tabColor = themePrefs.getInt("chatEmojiViewTabColor",
            AndroidUtilities.getIntDarkerColor("themeColor", -0x15));
    int lineColor = bgColor == 0xfff5f6f7 ? 0xffe2e5e7 : AndroidUtilities.setDarkColor(bgColor, 0x10);
    setOrientation(LinearLayout.VERTICAL);
    for (int i = 0; i < Emoji.data.length; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {/*from  ww w .j a  v a2 s.c om*/
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(Emoji.data[i]);
        gridView.setAdapter(emojiGridAdapter);
        //AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, bgColor);
        adapters.add(emojiGridAdapter);
    }

    if (needStickers) {
        GridView gridView = new GridView(context);
        gridView.setColumnWidth(AndroidUtilities.dp(72));
        gridView.setNumColumns(-1);
        gridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        gridView.setClipToPadding(false);
        views.add(gridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        gridView.setAdapter(stickersGridAdapter);
        //AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, bgColor);
    }

    //setBackgroundColor(0xfff5f6f7);
    setBackgroundColor(bgColor);

    pager = new ViewPager(context);
    pager.setAdapter(new EmojiPagesAdapter());

    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
    //linearLayout.setBackgroundColor(0xfff5f6f7);
    linearLayout.setBackgroundColor(bgColor);
    addView(linearLayout, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, AndroidUtilities.dp(48)));

    PagerSlidingTabStrip tabs = new PagerSlidingTabStrip(context);
    tabs.setViewPager(pager);
    tabs.setShouldExpand(true);
    tabs.setIndicatorHeight(AndroidUtilities.dp(2));
    tabs.setUnderlineHeight(AndroidUtilities.dp(1));
    //tabs.setIndicatorColor(0xff2b96e2);
    tabs.setIndicatorColor(tabColor);
    //tabs.setUnderlineColor(0xffe2e5e7);
    tabs.setUnderlineColor(lineColor);
    linearLayout.addView(tabs, new LinearLayout.LayoutParams(0, AndroidUtilities.dp(48), 1.0f));

    FrameLayout frameLayout = new FrameLayout(context);
    linearLayout.addView(frameLayout,
            new LinearLayout.LayoutParams(AndroidUtilities.dp(52), AndroidUtilities.dp(48)));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (EmojiView.this.listener != null && EmojiView.this.listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton,
            new FrameLayout.LayoutParams(AndroidUtilities.dp(52), AndroidUtilities.dp(48)));

    View view = new View(context);
    //view.setBackgroundColor(0xffe2e5e7);
    view.setBackgroundColor(lineColor);
    frameLayout.addView(view, new FrameLayout.LayoutParams(AndroidUtilities.dp(52), AndroidUtilities.dp(1),
            Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager);

    loadRecents();

    if (Emoji.data[0] == null || Emoji.data[0].length == 0) {
        pager.setCurrentItem(1);
    }

}

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {/* ww w.  j ava  2 s .com*/
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * //from w  w w  .ja  v  a 2 s.  c om
 * @param provider
 *            The provider used for the authentication process
 * @param startUrl
 *            The initial URL for the authentication process
 * @param endUrl
 *            The final URL for the authentication process
 * @param context
 *            The context used to create the authentication dialog
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
private void showLoginUI(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });
    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished
            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.itude.mobile.mobbl.core.controller.util.MBBasicViewController.java

public View addCloseButtonToClosableDialogView(View dialogView, final AlertDialog dialogToCloseOnclick) {
    MBStyleHandler styleHandler = MBViewBuilderFactory.getInstance().getStyleHandler();

    FragmentActivity context = getActivity();
    LinearLayout wrapper = new LinearLayout(context);
    wrapper.setOrientation(LinearLayout.VERTICAL);

    styleHandler.styleDialogCloseButtonWrapper(wrapper);

    LayoutParams prevDialogViewParams = dialogView.getLayoutParams();
    int width = LayoutParams.MATCH_PARENT;
    int height = LayoutParams.MATCH_PARENT;

    if (prevDialogViewParams != null) {
        width = prevDialogViewParams.width;
        height = prevDialogViewParams.height;
    }//from   w  ww .  j a  va2  s.  com

    LinearLayout.LayoutParams dialogViewParams = new LinearLayout.LayoutParams(width, height);
    dialogView.setLayoutParams(dialogViewParams);
    wrapper.addView(dialogView);

    LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);

    Button closeButton = new Button(context);
    closeButton.setLayoutParams(buttonParams);
    closeButton.setText(MBLocalizationService.getInstance().getTextForKey("Close"));
    styleHandler.styleDialogCloseButton(closeButton);
    closeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MBViewManager.getInstance().endDialog(getDialogController().getName(), false);
        }
    });

    wrapper.addView(closeButton);

    return wrapper;
}

From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java

/** Called when the activity is first created. */
@Override/*w  w  w.  ja v  a2 s .c om*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        SocketImplHookFactory.initialize();
    }
    {
        ProxySelector proxySelector = ProxySelector.getDefault();
        Log.d(TAG, "proxySelector=" + proxySelector);
        if (null != proxySelector) {
            URI uri = null;
            try {
                uri = new URI("http://www.google.com/");
            } catch (URISyntaxException e) {
                Log.d(TAG, e.toString());
            }
            List<Proxy> proxies = proxySelector.select(uri);
            if (null != proxies) {
                for (final Proxy proxy : proxies) {
                    Log.d(TAG, " proxy=" + proxy);
                }
            }
        }
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

public void imgShow(Bitmap bitmap, String strImgMsg) {
    MainActivity.adlib.put(strImgMsg, bitmap);
    Log.d("Portal", "Added an image. Size is now " + MainActivity.adlib.size());
    Log.i("Portal", "Image added for key " + strImgMsg);

    if (MainActivity.myGallery == null)
        return;//from ww  w  . j ava2 s .c o m

    if (MainActivity.gal_size < MainActivity.adlib.size()) { //new image has been added and the layout is initialized
        LinearLayout superLL = (LinearLayout) MainActivity.myGallery.getParent().getParent();

        if (MainActivity.gal_size < 1) {
            ImageView imgSplash = (ImageView) superLL.findViewById(R.id.imgSplash);
            imgSplash.setVisibility(View.INVISIBLE);
        }

        LinearLayout layout = new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        layout.setGravity(Gravity.CENTER);

        ImageView imageview = new ImageView(getApplicationContext());
        imageview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1000));
        imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageview.setImageBitmap(bitmap);

        //Add a button to go with it
        Button btnBuy = new Button(getApplicationContext());
        LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        btnParams.setMargins(-10, -10, -10, -10);
        btnBuy.setLayoutParams(btnParams);
        btnBuy.setText("Buy Now (" + strImgMsg + ")");
        btnBuy.setBackgroundColor(MainActivity.getDominantColor(bitmap));
        btnBuy.setTextColor(Color.WHITE);

        btnBuy.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent newActivity = new Intent(getApplicationContext(), WebActivity.class);
                newActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                newActivity.putExtra("URL", "https://portal-battlehack.herokuapp.com/");
                startActivity(newActivity);
            }
        });

        layout.addView(imageview);
        layout.addView(btnBuy);
        MainActivity.myGallery.addView(layout);
        MainActivity.gal_size++;
    }

}

From source file:edu.rowan.app.fragments.FoodRatingFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    LinearLayout view = new LinearLayout(getActivity());
    view.setOrientation(LinearLayout.VERTICAL);
    // view pager indicator
    TitlePageIndicator pageIndicator = new TitlePageIndicator(getActivity());
    pageIndicator.setBackgroundResource(R.color.rowanBrown);
    fragmentPager = new ViewPager(getActivity());
    fragmentPager.setId(VIEW_PAGER_ID);//from w ww. jav a2s. c  om
    fragmentAdapter = new FoodRatingAdapter(getChildFragmentManager());
    fragmentPager.setAdapter(fragmentAdapter);
    //View view = inflater.inflate(R.layout.activity_main, container, false);

    pageIndicator.setViewPager(fragmentPager);
    view.addView(pageIndicator);
    view.addView(fragmentPager);
    return view;
}

From source file:com.achep.header2actionbar.HeaderFragmentSupportV4.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final Activity activity = getActivity();
    assert activity != null;
    mFrameLayout = new FrameLayout(activity);

    mHeader = onCreateHeaderView(inflater, mFrameLayout);
    mHeaderHeader = mHeader.findViewById(android.R.id.title);
    mHeaderBackground = mHeader.findViewById(android.R.id.background);
    assert mHeader.getLayoutParams() != null;
    mHeader.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    mHeaderHeight = mHeader.getMeasuredHeight();

    mFakeHeader = new Space(activity);

    View content = onCreateContentView(inflater, mFrameLayout);
    mContentView = content;//from ww w.j a  v a2s  . c  om
    Log.i(TAG, "container:" + container.getMeasuredHeight() + ",mHeaderHeight=" + mHeaderHeight);

    final View topContentView = container;

    if (content instanceof ListView) {
        isListViewEmpty = true;

        final ListView listView = (ListView) content;
        mFakeHeader.setLayoutParams(new ListView.LayoutParams(0, mHeaderHeight));
        listView.addHeaderView(mFakeHeader);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (mOnScrollListener != null) {
                    mOnScrollListener.onScrollStateChanged(absListView, scrollState);
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (isListViewEmpty) {
                    scrollHeaderTo(0);
                } else {
                    final View child = absListView.getChildAt(0);
                    assert child != null;
                    scrollHeaderTo(child == mFakeHeader ? child.getTop() : -mHeaderHeight);
                }
            }
        });
    } else {
        topContentView.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        //Remove it here unless you want to get this callback for EVERY
                        //layout pass, which can get you into infinite loops if you ever
                        //modify the layout from within this method.
                        topContentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                        //Now you can get the width and height from content
                        int actionBarHeight = 0;
                        TypedValue tv = new TypedValue();
                        if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
                                    getResources().getDisplayMetrics());
                        }
                        Log.i(TAG, "topContentView:" + topContentView.getHeight() + ", actionBarHeight:"
                                + actionBarHeight + ", getStatusBarHeight:" + getStatusBarHeight());
                        ViewGroup.LayoutParams lp = mContentView.getLayoutParams();
                        lp.height = topContentView.getHeight() - actionBarHeight - getStatusBarHeight();
                        mContentView.setLayoutParams(lp);
                    }
                });

        // Merge fake header view and content view.
        final LinearLayout view = new LinearLayout(activity);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        view.setOrientation(LinearLayout.VERTICAL);
        mFakeHeader.setLayoutParams(new LinearLayout.LayoutParams(0, mHeaderHeight));
        view.addView(mFakeHeader);
        view.addView(content);

        // Put merged content to ScrollView
        final NotifyingScrollView scrollView = new NotifyingScrollView(activity);
        scrollView.addView(view);
        scrollView.setVerticalScrollBarEnabled(false);
        scrollView.setOverScrollMode(ScrollView.OVER_SCROLL_NEVER);
        scrollView.setOnScrollChangedListener(new NotifyingScrollView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
                Log.i(TAG, "onScrollChanged scroll ot -t :" + (-t));
                scrollHeaderTo(-t);
            }
        });
        mContentWrapper = scrollView;
        content = scrollView;
    }

    mFrameLayout.addView(content);
    mFrameLayout.addView(mHeader);

    // Content overlay view always shows at the top of content.
    if ((mContentOverlay = onCreateContentOverlayView(inflater, mFrameLayout)) != null) {
        mFrameLayout.addView(mContentOverlay, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    // Post initial scroll
    mFrameLayout.post(new Runnable() {
        @Override
        public void run() {
            Log.i(TAG, "post initial scroll to 0");
            // SEAN: walk around for scroll position bug
            if (mContentWrapper != null) {
                mContentWrapper.scrollTo(0, 0);
            }
            scrollHeaderTo(0, true);
        }
    });

    return mFrameLayout;
}