Example usage for android.widget EditText EditText

List of usage examples for android.widget EditText EditText

Introduction

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

Prototype

public EditText(Context context) 

Source Link

Usage

From source file:com.eugene.fithealthmaingit.UI.ManualEntrySaveMealFragment.java

private void updateItems() {
    mToolbar.setNavigationIcon(R.mipmap.ic_arrow_back);
    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override/*from  w  w  w. j  av a2  s.co m*/
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ChooseAddMealActivity.class);
            intent.putExtra(Globals.MEAL_TYPE, mealType);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    });
    mToolbar.inflateMenu(R.menu.menu_user_info);
    mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            if (menuItem.getItemId() == R.id.action_save)
                saveMeal();
            return false;
        }
    });
    mServingSizeUpdated.setText("1");

    LinearLayout changeServing = (LinearLayout) v.findViewById(R.id.changeServing);
    changeServing.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

            alert.setTitle("Update Serving Size: ");
            alert.setMessage("Servings Consumed");

            final EditText input = new EditText(getActivity());
            input.setText(mServingg.getText().toString());
            input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            input.selectAll();
            input.setGravity(Gravity.CENTER_HORIZONTAL);
            alert.setView(input, 64, 0, 64, 0);
            alert.setPositiveButton("Update", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    double values = Double.valueOf(input.getText().toString());
                    mServingg.setText(df.format(values));
                    mServingSizeUpdated.setText(df.format(values));
                    mCalUpdate.setText(dfW.format(Double.valueOf(mCalories) * values));
                    mCalorieProgress = Double.valueOf(mCalories) * values;
                    mFattieUpdate.setText(df.format(Double.valueOf(mFat) * values));
                    mFatProgress = Double.valueOf(mFat) * values;
                    mSaturatedFatUpdate.setText(df.format(Double.valueOf(mSaturatedFat) * values));
                    mCholesterolUpdate.setText(df.format(Double.valueOf(mCholesterol) * values));
                    mSodiumUpdate.setText(df.format(Double.valueOf(mSodium) * values));
                    mCarbUpdate.setText(df.format(Double.valueOf(mCarbohydrates) * values));
                    mCarbProgress = Double.valueOf(mCarbohydrates) * values;
                    mFiberUpdate.setText(df.format(Double.valueOf(mFiber) * values));
                    mSugarUpdate.setText(df.format(Double.valueOf(mSugar) * values));
                    mProUpdate.setText(df.format(Double.valueOf(mProtein) * values));
                    mProteinProgress = Double.valueOf(mProtein) * values;
                    mVitAUpdate.setText(df.format(Double.valueOf(mVitA) * values));
                    mVitCUpdate.setText(df.format(Double.valueOf(mVitC) * values));
                    mCalciumUpdate.setText(df.format(Double.valueOf(mCalcium) * values));
                    mIronUpdate.setText(df.format(Double.valueOf(mIron) * values));
                    progressBars();
                    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(input.getWindowToken(), 0);
                }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(input.getWindowToken(), 0);
                }
            });
            alert.setCancelable(false);
            alert.show();
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    });

}

From source file:com.codeskraps.sbrowser.home.SBrowserActivity.java

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnWww:
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle(getResources().getString(R.string.alertHttpTitle));
        alert.setMessage(getResources().getString(R.string.alertHttpSummary));
        final EditText input = new EditText(this);
        String url = webView == null ? null : webView.getUrl();
        if (url != null)
            input.setText(url);//from w  w  w  . j av a  2 s. c o  m
        alert.setView(input);
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString().trim();
                if (value.startsWith("http"))
                    webView.loadUrl(value);
                else
                    webView.loadUrl("http://" + value);
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        });
        alert.show();
        break;

    case R.id.btnHome:
        webView.loadUrl(sBrowserData.getetxtHome());
        break;

    case R.id.btnRight:
        webView.goForward();
        break;

    case R.id.btnRefresh:
        if (wF != null && wF.isReloading() == false) {
            webView.reload();
        } else {
            webView.stopLoading();
        }
        break;

    case R.id.btnSearch:
        doSearch();
        break;

    case R.id.btnMenu:
        Log.v(TAG, "Menu pressed");
        openOptionsMenu();
        break;
    }
}

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

private void addNewNoteTypeDialog() {

    String add = getResources().getString(R.string.model_browser_add_add);
    String clone = getResources().getString(R.string.model_browser_add_clone);

    // AnkiDroid doesn't have stdmodels class or model name localization, this could be much cleaner if implemented
    final String basicName = "Basic";
    final String addForwardReverseName = "Basic (and reversed card)";
    final String addForwardOptionalReverseName = "Basic (optional reversed card)";
    final String addClozeModelName = "Cloze";

    //Populates arrayadapters listing the mModels (includes prefixes/suffixes)
    mNewModelLabels = new ArrayList<>();

    //Used to fetch model names
    mNewModelNames = new ArrayList<>();
    mNewModelLabels.add(String.format(add, basicName));
    mNewModelLabels.add(String.format(add, addForwardReverseName));
    mNewModelLabels.add(String.format(add, addForwardOptionalReverseName));
    mNewModelLabels.add(String.format(add, addClozeModelName));

    mNewModelNames.add(basicName);//from  w ww .j  av  a2  s . c  o m
    mNewModelNames.add(addForwardReverseName);
    mNewModelNames.add(addForwardOptionalReverseName);
    mNewModelNames.add(addClozeModelName);

    final int numStdModels = mNewModelLabels.size();

    if (mModels != null) {
        for (JSONObject model : mModels) {
            try {
                mNewModelLabels.add(String.format(clone, model.getString("name")));
                mNewModelNames.add(model.getString("name"));
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
    }

    final Spinner addSelectionSpinner = new Spinner(this);
    ArrayAdapter<String> mNewModelAdapter = new ArrayAdapter<>(this, R.layout.dropdown_deck_item,
            mNewModelLabels);

    addSelectionSpinner.setAdapter(mNewModelAdapter);

    new MaterialDialog.Builder(this).title(R.string.model_browser_add).positiveText(R.string.dialog_ok)
            .customView(addSelectionSpinner, true).callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog dialog) {
                    mModelNameInput = new EditText(ModelBrowser.this);
                    mModelNameInput.setSingleLine();

                    //Temporary workaround - Lack of stdmodels class
                    if (addSelectionSpinner.getSelectedItemPosition() < numStdModels) {
                        mModelNameInput.setText(randomizeName(
                                mNewModelNames.get(addSelectionSpinner.getSelectedItemPosition())));
                    } else {
                        mModelNameInput
                                .setText(mNewModelNames.get(addSelectionSpinner.getSelectedItemPosition()) + " "
                                        + getResources().getString(R.string.model_clone_suffix));
                    }

                    mModelNameInput.setSelection(mModelNameInput.getText().length());

                    //Create textbox to name new model
                    new MaterialDialog.Builder(ModelBrowser.this).title(R.string.model_browser_add)
                            .positiveText(R.string.dialog_ok).customView(mModelNameInput, true)
                            .callback(new MaterialDialog.ButtonCallback() {
                                @Override
                                public void onPositive(MaterialDialog dialog) {
                                    String modelName = mModelNameInput.getText().toString();
                                    addNewNoteType(modelName, addSelectionSpinner.getSelectedItemPosition());
                                }
                            }).negativeText(R.string.dialog_cancel).show();
                }
            }).negativeText(R.string.dialog_cancel).show();
}

From source file:com.amazonaws.youruserpools.UserActivity.java

private void showUserDetail(final String attributeType, final String attributeValue) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(attributeType);/*from   ww w  .  j  a v  a2 s.  co m*/
    final EditText input = new EditText(UserActivity.this);
    input.setText(attributeValue);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);

    input.setLayoutParams(lp);
    input.requestFocus();
    builder.setView(input);

    builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                String newValue = input.getText().toString();
                if (!newValue.equals(attributeValue)) {
                    showWaitDialog("Updating...");
                    updateAttribute(AppHelper.getSignUpFieldsC2O().get(attributeType), newValue);
                }
                userDialog.dismiss();
            } catch (Exception e) {
                // Log failure
            }
        }
    }).setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                userDialog.dismiss();
                deleteAttribute(AppHelper.getSignUpFieldsC2O().get(attributeType));
            } catch (Exception e) {
                // Log failure
            }
        }
    });
    userDialog = builder.create();
    userDialog.show();
}

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

public void refreshLabels(JSONObject jObject) {

    /* Button btn = new Button(this);
      btn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
    getResources().getDimensionPixelSize(R.dimen.prediction_text_view_height) ));
    btn.setTextSize(pixels);// ww  w .  ja  va  2s .c o m
    btn.setText("Cat");
    predictions.addView(btn); */
    final List<RadioButton> buttons = new ArrayList<>();

    String result = "I think it's: ";
    try {
        JSONArray jArray = jObject.getJSONArray("data");
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject prediction = jArray.getJSONObject(i);
            // Pulling items from the array
            int score = prediction.getInt("score");
            if (score < Constants.minScoreThershold) {
                continue;
            }
            String label = prediction.getString("label");

            result += "\"" + label + "\" : " + score + "% ";

            RadioButton radioButton = new RadioButton(EasyPaint.this);
            radioButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    getResources().getDimensionPixelSize(R.dimen.prediction_text_view_height)));
            radioButton.setTextSize(pixels5);
            radioButton.setText(label + " (" + score + "%)");
            radioButton.setTag(label);
            //radioButton.set
            //predictions.addView(radioButton);
            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    saveButton.setTag(view.getTag());
                    feedbackType = ApiCallType.POSITIVE_FEEDBACK;
                }
            });

            buttons.add(radioButton);

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    final RadioButton radioButton = new RadioButton(EasyPaint.this);
    radioButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            getResources().getDimensionPixelSize(R.dimen.prediction_text_view_height)));
    radioButton.setTextSize(pixels5);
    radioButton.setText(R.string.other_label);
    buttons.add(radioButton);

    radioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder builder = new AlertDialog.Builder(EasyPaint.this);
            builder.setTitle(R.string.other_label);

            // Set up the input
            final EditText input = new EditText(EasyPaint.this);
            // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
            input.setInputType(InputType.TYPE_CLASS_TEXT);
            builder.setView(input);

            // Set up the buttons
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (input.getText().toString().length() > 0) {
                        radioButton.setText(input.getText().toString());
                        saveButton.setTag(input.getText().toString());
                        feedbackType = ApiCallType.NEGATIVE_FEEDBACK;
                    } else {
                        EasyPaint.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "You didn't specify a name, try again please", Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                        saveButton.setTag("");
                        feedbackType = ApiCallType.POSITIVE_FEEDBACK;
                        dialog.cancel();
                    }
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    saveButton.setTag("");
                    feedbackType = ApiCallType.POSITIVE_FEEDBACK;
                    dialog.cancel();
                }
            });

            builder.show();
        }
    });

    saveButton.setOnClickListener(otherLabelOnClickListener);

    toastMessage = result;

    EasyPaint.this.runOnUiThread(new Runnable() {
        public void run() {
            resetPredictionsView(predictions, false);
            Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_LONG).show();
            for (RadioButton r : buttons) {
                predictions.addView(r);
            }
        }
    });

}

From source file:com.krayzk9s.imgurholo.activities.MainActivity.java

private void displayUpload() {
    new AlertDialog.Builder(this).setTitle(R.string.dialog_upload_options_title)
            .setItems(R.array.upload_options, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    Intent intent;//from  w ww. ja  v a  2  s.c om
                    MainActivity activity = MainActivity.this;
                    switch (whichButton) {
                    case 0:
                        final EditText urlText = new EditText(activity);
                        urlText.setSingleLine();
                        new AlertDialog.Builder(activity).setTitle(R.string.dialog_url_title).setView(urlText)
                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        if (urlText.getText() != null) {
                                            UrlAsync urlAsync = new UrlAsync(urlText.getText().toString(),
                                                    apiCall);
                                            urlAsync.execute();
                                        }
                                    }
                                }).setNegativeButton(R.string.dialog_answer_cancel,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                // Do nothing.
                                            }
                                        })
                                .show();
                        break;
                    case 1:
                        intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        startActivityForResult(Intent.createChooser(intent, "Select Picture"), 3);
                        break;
                    case 2:
                        intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        startActivityForResult(intent, 4);
                        break;
                    case 3:
                        new AlertDialog.Builder(activity).setTitle(R.string.dialog_explanation_title)
                                .setMessage(R.string.dialog_explanation_summary)
                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        //do nothing
                                    }
                                }).show();
                    default:
                        break;
                    }
                }
            }).setNegativeButton(R.string.dialog_answer_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Do nothing.
                }
            }).show();
}

From source file:co.nerdart.ourss.fragment.FeedsListFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    setFeedSortEnabled(false);//w w w  . ja  v a  2  s. co  m

    switch (item.getItemId()) {
    case R.id.menu_add_feed: {
        startActivity(new Intent(Intent.ACTION_INSERT).setData(FeedColumns.CONTENT_URI));
        return true;
    }
    case R.id.menu_refresh: {
        if (!FetcherService.isRefreshingFeeds) {
            getActivity().startService(
                    new Intent(getActivity(), FetcherService.class).setAction(Constants.ACTION_REFRESH_FEEDS));
        }
        return true;
    }
    case R.id.menu_settings: {
        startActivity(new Intent(getActivity(), GeneralPrefsActivity.class));
        return true;
    }
    case R.id.menu_all_read: {
        new Thread() {
            @Override
            public void run() {
                ContentResolver cr = getActivity().getContentResolver();
                if (cr.update(EntryColumns.CONTENT_URI, FeedData.getReadContentValues(),
                        EntryColumns.WHERE_UNREAD, null) > 0) {
                    cr.notifyChange(FeedColumns.CONTENT_URI, null);
                    cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
                    cr.notifyChange(EntryColumns.FAVORITES_CONTENT_URI, null);
                }
            }
        }.start();
        return true;
    }
    case R.id.menu_add_group: {
        final EditText input = new EditText(getActivity());
        input.setSingleLine(true);
        new AlertDialog.Builder(getActivity()) //
                .setTitle(R.string.add_group_title) //
                .setView(input) //
                // .setMessage(R.string.add_group_sentence) //
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread() {
                            @Override
                            public void run() {
                                String groupName = input.getText().toString();
                                if (!groupName.isEmpty()) {
                                    ContentResolver cr = getActivity().getContentResolver();
                                    ContentValues values = new ContentValues();
                                    values.put(FeedColumns.IS_GROUP, true);
                                    values.put(FeedColumns.NAME, groupName);
                                    cr.insert(FeedColumns.GROUPS_CONTENT_URI, values);
                                }
                            }
                        }.start();
                    }
                }).setNegativeButton(android.R.string.cancel, null).show();
        return true;
    }
    case R.id.menu_import: {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            builder.setTitle(R.string.select_file);

            try {
                final String[] fileNames = Environment.getExternalStorageDirectory().list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        return new File(dir, filename).isFile();
                    }
                });
                builder.setItems(fileNames, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        new Thread(new Runnable() { // To not block the UI
                            @Override
                            public void run() {
                                try {
                                    OPML.importFromFile(Environment.getExternalStorageDirectory().toString()
                                            + File.separator + fileNames[which]);
                                } catch (Exception e) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Crouton.makeText(getActivity(), R.string.error_feed_import,
                                                    Style.INFO);
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                });
                builder.show();
            } catch (Exception e) {
                Crouton.makeText(getActivity(), R.string.error_feed_import, Style.INFO);
            }
        } else {
            Crouton.makeText(getActivity(), R.string.error_external_storage_not_available, Style.INFO);
        }

        return true;
    }
    case R.id.menu_export: {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {

            new Thread(new Runnable() { // To not block the UI
                @Override
                public void run() {
                    try {
                        final String filename = Environment.getExternalStorageDirectory().toString() + "/OURSS_"
                                + System.currentTimeMillis() + ".opml";

                        OPML.exportToFile(filename);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //Toast.makeText(getActivity(),
                                //      String.format
                                //  (getString(R.string.message_exported_to),
                                //    filename),Toast.LENGTH_LONG).show();
                                Crouton.makeText(getActivity(),
                                        String.format(getString(R.string.message_exported_to), filename),
                                        Style.INFO);
                            }
                        });
                    } catch (Exception e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //Toast.makeText(getActivity(),
                                //      R.string.error_feed_export,
                                //    Toast.LENGTH_LONG).show();
                                Crouton.makeText(getActivity(), R.string.error_feed_export, Style.INFO);
                            }
                        });
                    }
                }
            }).start();
        } else {
            //Toast.makeText(getActivity(), R.string.error_external_storage_not_available,
            //      Toast.LENGTH_LONG).show();
            Crouton.makeText(getActivity(), R.string.error_external_storage_not_available, Style.INFO);
        }
        break;
    }
    case R.id.menu_enable_feed_sort: {
        setFeedSortEnabled(true);
        return true;
    }
    case R.id.menu_disable_feed_sort: {
        // do nothing as the feed sort gets disabled anyway
        return true;
    }
    }

    return super.onOptionsItemSelected(item);
}

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

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

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

            return value;
        }

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

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

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

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

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

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

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

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input...
                                                        // Makes the text
                                                        // NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

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

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

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

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

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

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

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

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

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

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

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

From source file:com.tozny.e3db.android.DefaultKeyAuthenticator.java

@Override
public void getPassword(final PasswordHandler handler) {
    this.activity.runOnUiThread(new Runnable() {
        @Override/*  ww w . j  av  a2  s  .c  om*/
        public void run() {
            Context ctx = DefaultKeyAuthenticator.this.activity;

            final EditText input = new EditText(ctx);
            input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

            new AlertDialog.Builder(DefaultKeyAuthenticator.this.activity)
                    .setMessage(ctx.getString(R.string.key_provider_please_enter_pin))
                    .setPositiveButton(ctx.getString(R.string.key_provider_ok),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    try {
                                        handler.handlePassword(input.getText().toString());

                                    } catch (UnrecoverableKeyException e) {
                                        wrongPasswordCount[0]++;

                                        if (wrongPasswordCount[0] >= 3) {
                                            handler.handleError(
                                                    new RuntimeException("Too many password tries."));
                                        } else {
                                            Toast.makeText(DefaultKeyAuthenticator.this.activity,
                                                    e.getMessage(), Toast.LENGTH_SHORT).show();
                                            getPassword(handler);
                                        }
                                    }
                                }
                            })
                    .setNegativeButton(ctx.getString(R.string.key_provider_cancel),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    handler.handleCancel();
                                }
                            })
                    .setView(input).show();

            input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    if (input.isEnabled() && input.isFocusable()) {
                        input.post(new Runnable() {
                            @Override
                            public void run() {
                                final InputMethodManager imm = (InputMethodManager) DefaultKeyAuthenticator.this.activity
                                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
                            }
                        });
                    }
                }
            });
        }
    });
}

From source file:me.kaidul.uhunt.MainActivity.java

void ShowDialogUserNamePicker(String text) {
    final EditText input = new EditText(this);
    if (text != null)
        input.setText(text);/*from   w  w w  . j  av a2 s  .  c o  m*/

    new AlertDialog.Builder(this).setTitle("Add User").setMessage("Enter your Username").setView(input)
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String userName = input.getEditableText().toString();
                    if (userName.equals(prefs.getString(CommonUtils.KEY_USERNAME, "this_is_dummy"))) {
                        if (CommonUtils.isDebuggable) {
                            Log.d("skipped", "no need to send request!");
                        }
                        return;
                    }
                    prefs.edit().putString(CommonUtils.KEY_USERNAME, userName).commit();
                    userIDTask = new GetUserIdTask();
                    // Encoding userName
                    try {
                        userName = URLEncoder.encode(userName, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    userIDTask.execute(CommonUtils.USER_ID_TO_USERNAME + userName);
                }
            }).show();
}