Example usage for android.app Dialog setContentView

List of usage examples for android.app Dialog setContentView

Introduction

In this page you can find the example usage for android.app Dialog setContentView.

Prototype

public void setContentView(@NonNull View view) 

Source Link

Document

Set the screen content to an explicit view.

Usage

From source file:com.iskrembilen.quasseldroid.gui.LoginActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    final Dialog dialog;
    switch (id) {

    case R.id.DIALOG_EDIT_CORE: //fallthrough
    case R.id.DIALOG_ADD_CORE:
        dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_add_core);
        dialog.setTitle("Add new core");

        OnClickListener buttonListener = new OnClickListener() {

            @Override/*  w w w  .  java  2s.co m*/
            public void onClick(View v) {
                EditText nameField = (EditText) dialog.findViewById(R.id.dialog_name_field);
                EditText addressField = (EditText) dialog.findViewById(R.id.dialog_address_field);
                EditText portField = (EditText) dialog.findViewById(R.id.dialog_port_field);
                CheckBox sslBox = (CheckBox) dialog.findViewById(R.id.dialog_usessl_checkbox);
                if (v.getId() == R.id.cancel_button) {
                    nameField.setText("");
                    addressField.setText("");
                    portField.setText("");
                    sslBox.setChecked(false);
                    dialog.dismiss();

                } else if (v.getId() == R.id.save_button && !nameField.getText().toString().equals("")
                        && !addressField.getText().toString().equals("")
                        && !portField.getText().toString().equals("")) {
                    String name = nameField.getText().toString().trim();
                    String address = addressField.getText().toString().trim();
                    int port = Integer.parseInt(portField.getText().toString().trim());
                    boolean useSSL = sslBox.isChecked();

                    //TODO: Ken: mabye add some better check on what state the dialog is used for, edit/add. Atleast use a string from the resources so its the same if you change it.
                    if ((String) dialog.getWindow().getAttributes().getTitle() == "Add new core") {
                        dbHelper.addCore(name, address, port, useSSL);
                    } else if ((String) dialog.getWindow().getAttributes().getTitle() == "Edit core") {
                        dbHelper.updateCore(core.getSelectedItemId(), name, address, port, useSSL);
                    }
                    LoginActivity.this.updateCoreSpinner();
                    nameField.setText("");
                    addressField.setText("");
                    portField.setText("");
                    sslBox.setChecked(false);
                    dialog.dismiss();
                    if ((String) dialog.getWindow().getAttributes().getTitle() == "Add new core") {
                        Toast.makeText(LoginActivity.this, "Added core", Toast.LENGTH_LONG).show();
                    } else if ((String) dialog.getWindow().getAttributes().getTitle() == "Edit core") {
                        Toast.makeText(LoginActivity.this, "Edited core", Toast.LENGTH_LONG).show();
                    }
                }

            }
        };
        dialog.findViewById(R.id.cancel_button).setOnClickListener(buttonListener);
        dialog.findViewById(R.id.save_button).setOnClickListener(buttonListener);
        break;

    case R.id.DIALOG_NEW_CERTIFICATE:
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        final SharedPreferences certPrefs = getSharedPreferences("CertificateStorage", Context.MODE_PRIVATE);
        builder.setMessage("Received a new certificate, do you trust it?\n" + hashedCert).setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        certPrefs.edit().putString("certificate", hashedCert).commit();
                        onConnect.onClick(null);
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        dialog = builder.create();
        break;

    default:
        dialog = null;
        break;
    }
    return dialog;
}

From source file:com.orange.datavenue.StreamListFragment.java

/**
 *
 *///from  w  w  w . j  av a2  s . co m
private void createStream() {
    final android.app.Dialog dialog = new android.app.Dialog(getActivity());

    dialog.setContentView(R.layout.create_stream_dialog);

    dialog.setTitle(R.string.add_stream);

    final LinearLayout callbackLayout = (LinearLayout) dialog.findViewById(R.id.callback_layout);
    final EditText name = (EditText) dialog.findViewById(R.id.name);
    final EditText description = (EditText) dialog.findViewById(R.id.description);
    final EditText unit = (EditText) dialog.findViewById(R.id.unit);
    final EditText symbol = (EditText) dialog.findViewById(R.id.symbol);
    final EditText callback = (EditText) dialog.findViewById(R.id.callback);
    final EditText latitude = (EditText) dialog.findViewById(R.id.latitude);
    final EditText longitude = (EditText) dialog.findViewById(R.id.longitude);

    Button actionButton = (Button) dialog.findViewById(R.id.add_button);

    callbackLayout.setVisibility(View.VISIBLE);
    actionButton.setText(getString(R.string.add_stream));

    actionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG_NAME, "name : " + name.getText().toString());
            Log.d(TAG_NAME, "description : " + description.getText().toString());
            Log.d(TAG_NAME, "unit : " + unit.getText().toString());
            Log.d(TAG_NAME, "symbol : " + symbol.getText().toString());

            Stream newStream = new Stream();

            newStream.setName(name.getText().toString());
            newStream.setDescription(description.getText().toString());

            /**
             * Allocate new Location
             */
            Double[] location = null;

            String strLatitude = latitude.getText().toString();
            String strLongitude = longitude.getText().toString();

            try {
                if ((!"".equals(strLatitude)) && (!"".equals(strLongitude))) {
                    location = new Double[2];
                    location[0] = Double.parseDouble(strLatitude);
                    location[1] = Double.parseDouble(strLongitude);
                }
            } catch (NumberFormatException e) {
                Log.e(TAG_NAME, e.toString());
                location = null;
            }

            if (location != null) {
                newStream.setLocation(location);
            }
            /**************************************************************************/

            /**
             * Allocate new Unit & Symbol
             */
            Unit newUnit = null;
            String strUnit = unit.getText().toString();
            String strSymbol = symbol.getText().toString();

            if (!"".equals(strUnit)) {
                if (newUnit == null) {
                    newUnit = new Unit();
                }
                newUnit.setName(strUnit);
            }

            if (!"".equals(strSymbol)) {
                if (newUnit == null) {
                    newUnit = new Unit();
                }
                newUnit.setSymbol(strSymbol);
            }

            if (newUnit != null) {
                newStream.setUnit(newUnit);
            }

            /**
             * Allocate new Callback
             */
            Callback newCallback = null;
            String callbackUrl = callback.getText().toString();

            if (!"".equals(callbackUrl)) {
                try {
                    URL url = new URL(callbackUrl);
                    newCallback = new Callback();
                    newCallback.setUrl(url.toString());
                    newCallback.setName("Callback");
                    newCallback.setDescription("application callback");
                    newCallback.setStatus("activated");
                } catch (MalformedURLException e) {
                    Log.e(TAG_NAME, e.toString());
                    callback.setText("");
                }
            }

            if (newCallback != null) {
                newStream.setCallback(newCallback);
            }

            /**************************************************************************/

            CreateStreamOperation createStreamOperation = new CreateStreamOperation(Model.instance.oapiKey,
                    Model.instance.key, Model.instance.currentDatasource, newStream, new OperationCallback() {
                        @Override
                        public void process(Object object, Exception exception) {
                            if (exception == null) {
                                getStreams();
                            } else {
                                Errors.displayError(getActivity(), exception);
                            }
                        }
                    });

            createStreamOperation.execute("");

            dialog.dismiss();

        }
    });

    Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    dialog.setCancelable(false);
    dialog.show();
}

From source file:net.evendanan.android.hagarfingerpainting.HagarFingerpaintingActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_NEW_PAPER:
        final Dialog newPaper = new Dialog(this);
        newPaper.setTitle(R.string.new_paper_dialog_title);
        newPaper.setContentView(R.layout.new_paper_dialog);
        newPaper.setCancelable(true);/*  w  w  w .  j a  v a2 s .c o m*/
        final EditText painterName = (EditText) newPaper.findViewById(R.id.painter_name_input_text);
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/schoolbell.ttf");
        painterName.setTypeface(tf);

        final Gallery colors = (Gallery) newPaper.findViewById(R.id.colors_list);
        colors.setAdapter(new PaperColorListAdapter(getApplicationContext()));
        colors.setOnItemSelectedListener(new OnItemSelectedListener() {
            private View mSelectedItem = null;

            @Override
            public void onItemSelected(AdapterView<?> adapter, View v, int position, long id) {
                if (mSelectedItem != null)
                    mSelectedItem.setBackgroundDrawable(null);

                mSelectedItem = v;
                if (mSelectedItem != null)
                    mSelectedItem.setBackgroundResource(R.drawable.selected_color_background);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                if (mSelectedItem != null)
                    mSelectedItem.setBackgroundDrawable(null);
            }
        });

        colors.setSelection(2);

        View createButton = newPaper.findViewById(R.id.new_paper_create_button);
        createButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                Editor e = sp.edit();

                final CharSequence painterNameFromUI = painterName.getText().toString();
                final String newPainterName = TextUtils.isEmpty(painterNameFromUI)
                        ? getString(R.string.settings_key_painter_name_default_value)
                        : painterNameFromUI.toString();
                e.putString(getString(R.string.settings_key_painter_name), newPainterName);

                e.commit();

                PaperBackground paper = (PaperBackground) colors.getSelectedItem();

                newPaper.dismiss();

                createNewPaper(paper);
            }
        });
        View cancelButton = newPaper.findViewById(R.id.new_paper_cancel_button);
        cancelButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                newPaper.dismiss();
                if (!mPaperCreated)
                    HagarFingerpaintingActivity.this.finish();
            }
        });
        newPaper.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (!mPaperCreated)
                    HagarFingerpaintingActivity.this.finish();
            }
        });

        return newPaper;
    default:
        return super.onCreateDialog(id);
    }
}

From source file:com.example.google.playservices.placepicker.PlacePickerFragment.java

@Override
public void onCardClick(int cardActionId, String cardTag) {
    if (cardActionId == ACTION_PICK_PLACE) {
        // BEGIN_INCLUDE(intent)
        /* Use the PlacePicker Builder to construct an Intent.
        Note: This sample demonstrates a basic use case.
        The PlacePicker Builder supports additional properties such as search bounds.
         *//*from www .j a  v  a  2s  .  c o m*/
        try {
            PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
            Intent intent = intentBuilder.build(getActivity());
            // Start the Intent by requesting a result, identified by a request code.
            startActivityForResult(intent, REQUEST_PLACE_PICKER);

            // Hide the pick option in the UI to prevent users from starting the picker
            // multiple times.
            showPickAction(false);

        } catch (GooglePlayServicesRepairableException e) {
            GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), getActivity(), 0);
        } catch (GooglePlayServicesNotAvailableException e) {
            Toast.makeText(getActivity(), "Google Play Services is not available.", Toast.LENGTH_LONG).show();
        }

        // END_INCLUDE(intent)
    } else if (cardActionId == ACTION_REPORT_WAIT) {
        final Dialog dialog = new Dialog(this.getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.report);

        final NumberPicker np = (NumberPicker) dialog.findViewById(R.id.numpicker);
        np.setMaxValue(120);
        np.setMinValue(0);

        // Report
        Button dialogButtonReport = (Button) dialog.findViewById(R.id.dialogButtonReport);
        dialogButtonReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpPost httppost = new HttpPost("http://powergrid.xyz/quickq/restaurantpost.php");
                httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
                List<NameValuePair> nameValuePairs = new ArrayList<>(2);
                // TODO
                nameValuePairs.add(new BasicNameValuePair("placeid", globalplace.getId()));
                nameValuePairs.add(new BasicNameValuePair("waittime", String.valueOf(np.getValue())));
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                powergridServerReportTime task = new powergridServerReportTime();
                task.execute(httppost);

                dialog.dismiss();
            }
        });

        // Cancel
        Button dialogButtonCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);
        // If button is clicked, close the custom dialog
        dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }
}

From source file:com.vkassin.mtrade.Common.java

public static void putArcDeal(final Context ctx) {

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.arcdeal_dialog);
    dialog.setTitle(R.string.ArcDealDialogTitle);

    datetxt = (EditText) dialog.findViewById(R.id.expdateedit);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date dat1 = new Date();
    datetxt.setText(sdf.format(dat1));/*w ww . ja  v  a 2 s.  c o  m*/
    mYear = dat1.getYear() + 1900;
    mMonth = dat1.getMonth();
    mDay = dat1.getDate();
    final Date dat = new GregorianCalendar(mYear, mMonth, mDay).getTime();

    datetxt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i(TAG, "Show DatePickerDialog");
            DatePickerDialog dpd = new DatePickerDialog(ctx, mDateSetListener, mYear, mMonth, mDay);
            dpd.show();
        }
    });

    TextView itext = (TextView) dialog.findViewById(R.id.instrtext);
    itext.setText(Common.arcfilter);

    Button customDialog_Cancel = (Button) dialog.findViewById(R.id.cancelbutt);
    customDialog_Cancel.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.dismiss();
        }

    });

    Button customDialog_Put = (Button) dialog.findViewById(R.id.putorder);
    customDialog_Put.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            Double price = new Double(0);
            Long qval = new Long(0);
            final EditText pricetxt = (EditText) dialog.findViewById(R.id.priceedit);
            final EditText quanttxt = (EditText) dialog.findViewById(R.id.quantedit);

            try {

                price = Double.valueOf(pricetxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
                return;
            }
            try {

                qval = Long.valueOf(quanttxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
                return;
            }

            //            if (dat.compareTo(new GregorianCalendar(mYear, mMonth, mDay)
            //            .getTime()) > 0) {
            //
            //               Toast.makeText(ctx, R.string.CorrectDate,
            //               Toast.LENGTH_SHORT).show();
            //
            //            return;
            //            }

            long maxkey = 0;
            Iterator<String> itr2 = arcdealMap.keySet().iterator();
            while (itr2.hasNext()) {
                String key1 = itr2.next();
                long k = Long.parseLong(key1);
                if (k > maxkey)
                    maxkey = k;
            }

            Deal adeal = new Deal();
            Iterator<String> itr1 = instrMap.keySet().iterator();
            while (itr1.hasNext()) {
                String key1 = itr1.next();
                Instrument in = instrMap.get(key1);
                if (in.symbol.equals(Common.arcfilter)) {

                    adeal.instrId = Long.valueOf(in.id);
                    break;
                }
            }

            final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.radio0);

            adeal.price = price;
            adeal.qty = qval;
            adeal.dtime = new GregorianCalendar(mYear, mMonth, mDay).getTimeInMillis();
            adeal.direct = bu0.isChecked() ? Long.valueOf(0) : Long.valueOf(1);
            Collection<String> lacc = Common.getAccountList();
            adeal.account = (lacc == null) ? "" : lacc.iterator().next();
            arcdealMap.put(String.valueOf(maxkey + 1), adeal);
            Common.saveArcDeals();
            Common.arcActivity.refresh();
            dialog.dismiss();
        }
    });

    dialog.show();

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

}

From source file:com.medisa.myspacecal.MainActivity.java

@Override
public void onSideNavigationItemClick(int itemId) {
    switch (itemId) {
    case R.id.side_navigation_menu_calendario:
        range = 0;//from   ww  w  .  j a  v a  2s .  c  o m
        Intent i = new Intent(this, MainActivity.class);
        startActivity(i);
        break;
    case R.id.side_navigation_menu_date_range:
        // custom dialog
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.custom_range_date);
        dialog.setTitle("Data range");

        // set the custom dialog components - text, image and button
        final DatePicker dpStart = (DatePicker) dialog.findViewById(R.id.dpStart);
        final DatePicker dpEnd = (DatePicker) dialog.findViewById(R.id.dpEnd);
        Button btnSalva = (Button) dialog.findViewById(R.id.btnSalva);
        final CheckBox cbIntegralBox = (CheckBox) dialog.findViewById(R.id.cbIntegral);
        // if button is clicked, close the custom dialog
        btnSalva.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dateStart = Funzioni.addZero(dpStart.getDayOfMonth(), 2) + "-"
                        + Funzioni.addZero(dpStart.getMonth() + 1, 2) + "-" + dpStart.getYear();
                dateEnd = Funzioni.addZero(dpEnd.getDayOfMonth(), 2) + "-"
                        + Funzioni.addZero(dpEnd.getMonth() + 1, 2) + "-" + dpEnd.getYear();
                Log.e(dateStart, dateEnd);
                if (cbIntegralBox.isChecked()) {
                    //#########################JSON
                    AsyncHttpClient client = new AsyncHttpClient();
                    client.get("http://199.180.196.10/json/integral?startdate=" + dateStart + "&enddate="
                            + dateEnd, new AsyncHttpResponseHandler() {
                                @Override
                                public void onSuccess(String response) {
                                    Log.e("SCARICATO", response + "");
                                    JSONArray jObject;
                                    satellitiIntegral = new ArrayList<SatelliteIntegral>();
                                    try {
                                        jObject = new JSONArray(response);
                                        for (int i = 0; i < jObject.length(); i++) {
                                            JSONArray menuObject = jObject.getJSONArray(i);
                                            String dataStart = menuObject.getString(0);
                                            String dataEnd = menuObject.getString(1);
                                            String raj2000 = menuObject.getString(2);
                                            String decj2000 = menuObject.getString(3);
                                            String target = menuObject.getString(4);
                                            Log.e("", dataStart + " " + dataEnd + " " + raj2000 + " " + decj2000
                                                    + " " + target);
                                            satellitiIntegral.add(new SatelliteIntegral(dataStart, dataEnd,
                                                    raj2000, decj2000, target));
                                        }
                                        adapter = new GridCellAdapter(getApplicationContext(),
                                                R.id.day_gridcell, month, year);
                                        adapter.notifyDataSetChanged();
                                        calendarView.setAdapter(adapter);

                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            });
                }

                dialog.dismiss();
                //###############################################
                //                   Intent mioIntent= new Intent(ctx, MainActivity.class);
                //                   startActivity(mioIntent);
            }

        });
        dialog.show();
        break;
    //            case R.id.side_navigation_menu_item3:
    //                invokeActivity(getString(R.string.title3), R.drawable.ic_android3);
    //                break;
    //
    //            case R.id.side_navigation_menu_item4:
    //                invokeActivity(getString(R.string.title4), R.drawable.ic_android4);
    //                break;
    //
    //            case R.id.side_navigation_menu_item5:
    //                invokeActivity(getString(R.string.title5), R.drawable.ic_android5);
    //                break;

    default:
        return;
    }
}

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  av a2  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:org.tigase.mobile.chat.ChatHistoryFragment.java

private void showMessageDetails(final long id) {
    Cursor cc = null;//from   w  w w  .ja  v  a  2  s  .co m
    final java.text.DateFormat df = DateFormat.getDateFormat(getActivity());
    final java.text.DateFormat tf = DateFormat.getTimeFormat(getActivity());

    try {
        cc = getChatEntry(id);

        Dialog alertDialog = new Dialog(getActivity());
        alertDialog.setContentView(R.layout.chat_item_details_dialog);
        alertDialog.setCancelable(true);
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setTitle("Message details");

        TextView msgDetSender = (TextView) alertDialog.findViewById(R.id.msgDetSender);
        msgDetSender.setText(cc.getString(cc.getColumnIndex(ChatTableMetaData.FIELD_JID)));

        Date timestamp = new Date(cc.getLong(cc.getColumnIndex(ChatTableMetaData.FIELD_TIMESTAMP)));
        TextView msgDetReceived = (TextView) alertDialog.findViewById(R.id.msgDetReceived);
        msgDetReceived.setText(df.format(timestamp) + " " + tf.format(timestamp));

        final int state = cc.getInt(cc.getColumnIndex(ChatTableMetaData.FIELD_STATE));
        TextView msgDetState = (TextView) alertDialog.findViewById(R.id.msgDetState);
        switch (state) {
        case ChatTableMetaData.STATE_INCOMING:
            msgDetState.setText("Received");
            break;
        case ChatTableMetaData.STATE_OUT_SENT:
            msgDetState.setText("Sent");
            break;
        case ChatTableMetaData.STATE_OUT_NOT_SENT:
            msgDetState.setText("Not sent");
            break;
        default:
            msgDetState.setText("?");
            break;
        }

        alertDialog.show();
    } finally {
        if (cc != null && !cc.isClosed())
            cc.close();
    }
}

From source file:the.joevlc.MainActivity.java

private void showInfoDialog() {
    final Dialog infoDialog = new Dialog(this, R.style.info_dialog);
    infoDialog.setContentView(R.layout.info_dialog);
    Button okButton = (Button) infoDialog.findViewById(R.id.ok);
    okButton.setOnClickListener(new OnClickListener() {
        @Override/*from   w w w. j a  v  a2 s.  c  o  m*/
        public void onClick(View view) {
            CheckBox notShowAgain = (CheckBox) infoDialog.findViewById(R.id.not_show_again);
            if (notShowAgain.isChecked() && mSettings != null) {
                Editor editor = mSettings.edit();
                editor.putInt(PREF_SHOW_INFO, mVersionNumber);
                editor.commit();
            }
            /* Close the dialog */
            infoDialog.dismiss();
            /* and finally open the sliding menu if first run */
            if (mFirstRun)
                mMenu.showBehind();
        }
    });
    infoDialog.show();
}

From source file:edu.berkeley.boinc.BOINCActivity.java

/**
 * React to selection of nav bar item//from   w  w w. j a v  a 2s .c  om
 * @param item
 * @param position
 * @param init
 */
private void dispatchNavBarOnClick(NavDrawerItem item, boolean init) {
    // update the main content by replacing fragments
    if (item == null) {
        if (Logging.WARNING)
            Log.w(Logging.TAG, "dispatchNavBarOnClick returns, item null.");
        return;
    }
    if (Logging.DEBUG)
        Log.d(Logging.TAG, "dispatchNavBarOnClick for item with id: " + item.getId() + " title: "
                + item.getTitle() + " is project? " + item.isProjectItem());

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Boolean fragmentChanges = false;
    if (init) {
        // if init, setup status fragment
        ft.replace(R.id.status_container, new StatusFragment());
    }
    if (!item.isProjectItem()) {
        switch (item.getId()) {
        case R.string.tab_tasks:
            ft.replace(R.id.frame_container, new TasksFragment());
            fragmentChanges = true;
            break;
        case R.string.tab_notices:
            ft.replace(R.id.frame_container, new NoticesFragment());
            fragmentChanges = true;
            break;
        case R.string.tab_projects:
            ft.replace(R.id.frame_container, new ProjectsFragment());
            fragmentChanges = true;
            break;
        case R.string.menu_help:
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://boinc.berkeley.edu/wiki/BOINC_Help"));
            startActivity(i);
            break;
        case R.string.menu_about:
            final Dialog dialog = new Dialog(this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_about);
            Button returnB = (Button) dialog.findViewById(R.id.returnB);
            TextView tvVersion = (TextView) dialog.findViewById(R.id.version);
            try {
                tvVersion.setText(getString(R.string.about_version) + " "
                        + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
            } catch (NameNotFoundException e) {
                if (Logging.WARNING)
                    Log.w(Logging.TAG, "version name not found.");
            }

            returnB.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.show();
            break;
        case R.string.menu_eventlog:
            startActivity(new Intent(this, EventLogActivity.class));
            break;
        case R.string.projects_add:
            startActivity(new Intent(this, SelectionListActivity.class));
            break;
        case R.string.tab_preferences:
            ft.replace(R.id.frame_container, new PrefsFragment());
            fragmentChanges = true;
            break;

        default:
            if (Logging.ERROR)
                Log.d(Logging.TAG,
                        "dispatchNavBarOnClick() could not find corresponding fragment for " + item.getTitle());
            break;
        }

    } else {
        // ProjectDetailsFragment. Data shown based on given master URL
        Bundle args = new Bundle();
        args.putString("url", item.getProjectMasterUrl());
        Fragment frag = new ProjectDetailsFragment();
        frag.setArguments(args);
        ft.replace(R.id.frame_container, frag);
        fragmentChanges = true;
    }

    mDrawerLayout.closeDrawer(mDrawerList);

    if (fragmentChanges) {
        ft.commit();
        setTitle(item.getTitle());
        mDrawerListAdapter.selectedMenuId = item.getId(); //highlight item persistently
        mDrawerListAdapter.notifyDataSetChanged(); // force redraw
    }

    if (Logging.DEBUG)
        Log.d(Logging.TAG, "displayFragmentForNavDrawer() " + item.getTitle());
}