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.microsoft.windowsazure.mobileservices.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * /*from ww  w . ja v a2 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:jp.watnow.plugins.dialog.Notification.java

/**
 * Builds and shows a native Android prompt dialog with given title, message, buttons.
 * This dialog only shows up to 3 buttons.  Any labels after that will be ignored.
 * The following results are returned to the JavaScript callback identified by callbackId:
 *     buttonIndex         Index number of the button selected
 *     input1            The text entered in the prompt dialog box
 *
 * @param message           The message the dialog should display
 * @param title             The title of the dialog
 * @param buttonLabels      A comma separated list of button labels (Up to 3 buttons)
 * @param callbackContext   The callback context.
 *///from   w  ww  . ja  va 2 s .com
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels,
        final String defaultText, final String dialogType, final CallbackContext callbackContext) {

    final CordovaInterface cordova = this.cordova;

    Runnable runnable = new Runnable() {
        public void run() {
            final EditText promptInput = new EditText(cordova.getActivity());
            promptInput.setHint(defaultText);
            Log.d("DialogPlugin", dialogType);
            if (dialogType.equals(INPUT_SECURE)) {
                promptInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
            AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            dlg.setMessage(message);
            dlg.setTitle(title);
            dlg.setCancelable(false);

            dlg.setView(promptInput);

            final JSONObject result = new JSONObject();

            // First button
            if (buttonLabels.length() > 0) {
                try {
                    dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 1);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                }
            }

            // Second button
            if (buttonLabels.length() > 1) {
                try {
                    dlg.setNeutralButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 2);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                }
            }

            // Third button
            if (buttonLabels.length() > 2) {
                try {
                    dlg.setPositiveButton(buttonLabels.getString(2), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 3);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                }
            }
            dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    try {
                        result.put("buttonIndex", 0);
                        result.put("input1", promptInput.getText().toString().trim().length() == 0 ? defaultText
                                : promptInput.getText());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                }
            });

            changeTextDirection(dlg);
        };
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:reportsas.com.formulapp.Formulario.java

public LinearLayout obtenerLayout(LayoutInflater infla, Pregunta preg) {
    int id;//from www. j  a v a 2 s. c o  m
    int tipo_pregunta = preg.getTipoPregunta();
    LinearLayout pregunta;
    TextView textView;
    TextView textAyuda;
    switch (tipo_pregunta) {
    case 1:
        id = R.layout.pregunta_texto;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloPregunta);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        break;
    case 2:
        id = R.layout.pregunta_multitexto;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.mtxtTritulo);
        textAyuda = (TextView) pregunta.findViewById(R.id.mtxtAyuda);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());

        break;
    case 3:
        id = R.layout.pregunta_seleccion;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloSeleccion);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_seleccion);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        RadioGroup rg = (RadioGroup) pregunta.findViewById(R.id.opcionesUnica);
        ArrayList<OpcionForm> opciones = preg.getOpciones();
        final ArrayList<RadioButton> rb = new ArrayList<RadioButton>();

        for (int i = 0; i < opciones.size(); i++) {
            OpcionForm opcion = opciones.get(i);
            rb.add(new RadioButton(this));
            rg.addView(rb.get(i));
            rb.get(i).setText(opcion.getEtInicial());

        }
        final TextView respt = (TextView) pregunta.findViewById(R.id.respuestaGruop);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonID = group.getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton) group.findViewById(radioButtonID);
                respt.setText(radioButton.getText());
            }
        });

        break;
    case 4:
        id = R.layout.pregunta_multiple;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloMultiple);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_mltiple);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        ArrayList<OpcionForm> opciones2 = preg.getOpciones();
        final EditText ediOtros = new EditText(this);
        ArrayList<CheckBox> cb = new ArrayList<CheckBox>();

        for (int i = 0; i < opciones2.size(); i++) {
            OpcionForm opcion = opciones2.get(i);
            cb.add(new CheckBox(this));
            pregunta.addView(cb.get(i));
            cb.get(i).setText(opcion.getEtInicial());
            if (opcion.getEditble().equals("S")) {

                ediOtros.setEnabled(false);
                ediOtros.setId(R.id.edtTexto);
                pregunta.addView(ediOtros);
                cb.get(i).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            ediOtros.setEnabled(true);
                        } else {
                            ediOtros.setText("");
                            ediOtros.setEnabled(false);
                        }
                    }
                });
            }

        }
        TextView spacio = new TextView(this);
        spacio.setText("        ");
        spacio.setVisibility(View.INVISIBLE);
        pregunta.addView(spacio);
        break;
    case 5:
        id = R.layout.pregunta_escala;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloEscala);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_escala);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());

        TextView etInicial = (TextView) pregunta.findViewById(R.id.etInicial);
        TextView etFinal = (TextView) pregunta.findViewById(R.id.etFinal);
        OpcionForm opci = preg.getOpciones().get(0);
        etInicial.setText(opci.getEtInicial());
        etFinal.setText(opci.getEtFinal());
        final TextView respEscala = (TextView) pregunta.findViewById(R.id.seleEscala);
        RatingBar rtBar = (RatingBar) pregunta.findViewById(R.id.escala);
        rtBar.setNumStars(Integer.parseInt(opci.getValores().get(0).getDescripcion()));
        rtBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                respEscala.setText("" + Math.round(rating));
            }
        });

        break;
    case 6:
        id = R.layout.pregunta_lista;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloLista);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_lista);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        ArrayList<OpcionForm> opciones3 = preg.getOpciones();
        //Creamos la lista
        LinkedList<ObjetoSpinner> opcn = new LinkedList<ObjetoSpinner>();
        //La poblamos con los ejemplos
        for (int i = 0; i < opciones3.size(); i++) {
            opcn.add(new ObjetoSpinner(opciones3.get(i).getIdOpcion(), opciones3.get(i).getEtInicial()));
        }

        //Creamos el adaptador*/
        Spinner listad = (Spinner) pregunta.findViewById(R.id.opcionesListado);
        ArrayAdapter<ObjetoSpinner> spinner_adapter = new ArrayAdapter<ObjetoSpinner>(this,
                android.R.layout.simple_spinner_item, opcn);
        //Aadimos el layout para el men y se lo damos al spinner
        spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        listad.setAdapter(spinner_adapter);

        break;
    case 7:
        id = R.layout.pregunta_tabla;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloTabla);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_tabla);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        TableLayout tba = (TableLayout) pregunta.findViewById(R.id.tablaOpciones);
        ArrayList<OpcionForm> opciones4 = preg.getOpciones();
        ArrayList<RadioButton> radiosbotonoes = new ArrayList<RadioButton>();
        for (int i = 0; i < opciones4.size(); i++) {
            TableRow row = (TableRow) LayoutInflater.from(this).inflate(R.layout.row_pregunta_tabla, null);
            RadioGroup tg_valores = (RadioGroup) row.findViewById(R.id.valoresRow);

            final ArrayList<RadioButton> valoOpc = new ArrayList<RadioButton>();
            ArrayList<Valor> valoresT = opciones4.get(i).getValores();
            for (int k = 0; k < valoresT.size(); k++) {
                RadioButton rb_nuevo = new RadioButton(this);
                rb_nuevo.setText(valoresT.get(k).getDescripcion());
                tg_valores.addView(rb_nuevo);
                valoOpc.add(rb_nuevo);
            }

            ((TextView) row.findViewById(R.id.textoRow)).setText(opciones4.get(i).getEtInicial());
            tba.addView(row);
        }
        TextView espacio = new TextView(this);
        espacio.setText("        ");
        pregunta.addView(espacio);
        break;
    case 8:
        id = R.layout.pregunta_fecha;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloFecha);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_fecha);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());

        break;
    case 9:
        id = R.layout.pregunta_hora;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloHora);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_hora);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());

        break;
    default:
        id = R.layout.pregunta_multiple;
        pregunta = (LinearLayout) infla.inflate(id, null, false);

        textView = (TextView) pregunta.findViewById(R.id.TituloMultiple);
        textAyuda = (TextView) pregunta.findViewById(R.id.texto_ayuda_mltiple);
        textView.setText(preg.getOrden() + ". " + preg.getTitulo());
        textAyuda.setText(preg.getTxtAyuda());
        break;
    }

    return pregunta;
}

From source file:edu.stanford.mobisocial.dungbeetle.ui.fragments.FeedActionsFragment.java

public void broadcastGps() {
    final CharSequence[] items = { "5 minutes", "15 minutes", "1 hour", " 24 hours" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Choose duration of broadcast");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, final int item) {
            AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
            alert.setMessage("Enter a secret key if you want to:");
            final EditText input = new EditText(getActivity());
            alert.setView(input);/*  w  w  w  .ja va 2 s  .co m*/
            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    final String password = input.getText().toString();
                    myLocation = new MyLocation();
                    locationResult = new MyLocation.LocationResult() {
                        final ProgressDialog dialog = ProgressDialog.show(getActivity(), "",
                                "Preparing broadcast...", true);

                        @Override
                        public void gotLocation(final Location location) {
                            //Got the location!
                            try {
                                int minutes;
                                if (item == 0) {
                                    minutes = 5;
                                } else if (item == 1) {
                                    minutes = 15;
                                } else if (item == 2) {
                                    minutes = 60;
                                } else if (item == 3) {
                                    minutes = 1440;
                                } else {
                                    minutes = 5;
                                }

                                Uri uri = new Uri.Builder().scheme("http").authority("suif.stanford.edu")
                                        .path("dungbeetle/nearby.php").build();

                                StringBuffer sb = new StringBuffer();
                                DefaultHttpClient client = new DefaultHttpClient();
                                HttpPost httpPost = new HttpPost(uri.toString());

                                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                                nameValuePairs.add(new BasicNameValuePair("group_name", mGroupName));
                                nameValuePairs
                                        .add(new BasicNameValuePair("feed_uri", mExternalFeedUri.toString()));
                                nameValuePairs.add(new BasicNameValuePair("length", Integer.toString(minutes)));
                                nameValuePairs.add(
                                        new BasicNameValuePair("lat", Double.toString(location.getLatitude())));
                                nameValuePairs.add(new BasicNameValuePair("lng",
                                        Double.toString(location.getLongitude())));
                                nameValuePairs.add(new BasicNameValuePair("password", password));
                                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                try {
                                    HttpResponse execute = client.execute(httpPost);
                                    InputStream content = execute.getEntity().getContent();
                                    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                                    String s = "";
                                    while ((s = buffer.readLine()) != null) {
                                        sb.append(s);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                String response = sb.toString();
                                if (response.equals("1")) {
                                    Toast.makeText(getActivity(), "Now broadcasting for " + items[item],
                                            Toast.LENGTH_SHORT).show();
                                } else
                                    Log.w(TAG, "Wtf");

                                Log.w(TAG, "response: " + response);
                            } catch (Exception e) {
                            }

                            dialog.dismiss();
                        }
                    };
                    locationClick();
                }
            });
            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            });
            alert.show();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

From source file:nz.ac.otago.psyanlab.common.designer.program.stage.EditPropPropertiesFragment.java

/**
 * Creates an edit text entry field that allows the user to enter a string.
 * //from   w w  w  . j av  a 2 s.  c  om
 * @return EditText
 */
private View newStringInputView(String s) {
    EditText view = new EditText(getActivity());
    view.setInputType(InputType.TYPE_CLASS_TEXT);
    view.setSingleLine();
    view.setText(s);
    return view;
}

From source file:com.mendhak.gpslogger.common.PrefsIO.java

public void AskFileName() {

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(R.string.AskFileName);

    final EditText input = new EditText(context);
    input.setInputType(InputType.TYPE_CLASS_TEXT);

    int pos = curFileName.lastIndexOf(File.separator) + 1;
    String filename = "";
    if (pos > 0)
        filename = curFileName.substring(pos);
    pos = filename.lastIndexOf(extension);
    if (pos > 1)
        input.setText(filename.substring(0, pos - 1));
    else// w  ww . j av  a2s . co  m
        input.setText(defFileName);

    Utilities.LogDebug("Asking user the filename to use for export of settings");

    builder.setView(input);
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String str = input.getText().toString();
            String fname = "";
            if (str.length() > 0)
                fname = str.replaceAll(filter, "");
            if (fname.length() != 0) {
                curFileName = defPath + File.separator + fname + "." + extension;
                ExportFile();
            }
        }
    });
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    builder.show();
}

From source file:io.github.trulyfree.easyaspi.MainActivity.java

@Override
public boolean setup() {
    downloadHandler = new DownloadHandler(this);
    fileHandler = new FileHandler(this);
    moduleHandler = new ModuleHandler(this);
    executorService = Executors.newCachedThreadPool();

    setContentView(R.layout.activity_main);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override/*w  w w .  j a  va2 s  . c  o  m*/
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            ViewSwitcher viewGroup = (ViewSwitcher) findViewById(R.id.content);
            int id = item.getItemId();
            if ((id == R.id.navigation_home || id == R.id.navigation_modules) && id != currentID) {
                currentID = item.getItemId();
                viewGroup.showNext();
                return true;
            }
            return false;
        }

    });

    ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.content);
    Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
    Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
    viewSwitcher.setInAnimation(in);
    viewSwitcher.setOutAnimation(out);

    resetConfigReturned();

    Button getNewModule = (Button) findViewById(R.id.new_module_config_confirm);
    getNewModule.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText editText = (EditText) findViewById(R.id.new_module_config_configurl);
            final String url = editText.getText().toString();
            Toast.makeText(MainActivity.this, "Requested config from: " + url, Toast.LENGTH_SHORT).show();
            executorService.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() {
                    ModuleConfig config;
                    try {
                        config = moduleHandler.getModuleConfig(url);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Invalid URL. :(", Toast.LENGTH_LONG).show();
                            }
                        });
                        return false;
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Failed to get module config. :(",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                        return false;
                    } catch (JsonParseException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Config loaded was invalid. :(",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                        return false;
                    }

                    final ModuleConfig finalConfig = config;
                    final ImageView configResponseBlock = (ImageView) findViewById(R.id.block_module_returned);
                    final int colorFrom = ContextCompat.getColor(MainActivity.this, R.color.colorFillingTint);
                    final int colorTo = ContextCompat.getColor(MainActivity.this, R.color.colorClear);
                    final ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom,
                            colorTo);
                    colorAnimation.setDuration(ANIMATION_DURATION);
                    colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animator) {
                            configResponseBlock.setBackgroundColor((Integer) animator.getAnimatedValue());
                        }
                    });
                    colorAnimation.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {
                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            LinearLayout layout = (LinearLayout) findViewById(R.id.module_returned_config);
                            EditText moduleName = (EditText) findViewById(R.id.module_returned_configname);
                            EditText moduleVersion = (EditText) findViewById(
                                    R.id.module_returned_configversion);
                            EditText moduleConfigUrl = (EditText) findViewById(R.id.module_returned_configurl);
                            EditText moduleJarUrl = (EditText) findViewById(R.id.module_returned_jarurl);
                            LinearLayout moduleDependencies = (LinearLayout) findViewById(
                                    R.id.module_returned_dependencies);
                            moduleDependencies.removeAllViewsInLayout();
                            try {
                                configResponseBlock.setVisibility(View.GONE);
                                moduleName.setText(finalConfig.getName());
                                moduleVersion.setText(finalConfig.getVersion());
                                moduleConfigUrl.setText(finalConfig.getConfUrl());
                                moduleJarUrl.setText(finalConfig.getJarUrl());
                                Config[] dependencies = finalConfig.getDependencies();
                                for (Config dependency : dependencies) {
                                    LinearLayout dependencyLayout = new LinearLayout(MainActivity.this);
                                    dependencyLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                                            LayoutParams.WRAP_CONTENT));
                                    dependencyLayout.setOrientation(LinearLayout.HORIZONTAL);
                                    EditText name = new EditText(MainActivity.this);
                                    EditText jarUrl = new EditText(MainActivity.this);
                                    EditText[] loopThrough = { name, jarUrl };
                                    LayoutParams params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);
                                    for (EditText item : loopThrough) {
                                        item.setLayoutParams(params);
                                        item.setClickable(false);
                                        item.setInputType(InputType.TYPE_NULL);
                                        item.setCursorVisible(false);
                                        item.setFocusable(false);
                                        item.setFocusableInTouchMode(false);
                                    }
                                    name.setText(dependency.getName());
                                    jarUrl.setText(dependency.getJarUrl());
                                    dependencyLayout.addView(name);
                                    dependencyLayout.addView(jarUrl);
                                    moduleDependencies.addView(dependencyLayout);
                                }
                                layout.setClickable(true);
                                Button validate = (Button) findViewById(R.id.module_returned_validate);
                                Button cancel = (Button) findViewById(R.id.module_returned_cancel);
                                validate.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Toast.makeText(MainActivity.this, "Requesting jars...",
                                                Toast.LENGTH_SHORT).show();
                                        executorService.submit(new Callable<Boolean>() {
                                            @Override
                                            public Boolean call() {
                                                try {
                                                    boolean success = true, refreshAllModification = true;
                                                    Button refreshAll = null,
                                                            getNewModule = (Button) findViewById(
                                                                    R.id.new_module_config_confirm);
                                                    try {
                                                        refreshAll = (Button) findViewById(R.id.refresh_all);
                                                        refreshAll.setClickable(false);
                                                    } catch (Throwable e) {
                                                        refreshAllModification = false;
                                                    }
                                                    getNewModule.setClickable(false);
                                                    final TextView stager = (TextView) findViewById(
                                                            R.id.new_module_config_downloadstage);
                                                    final ProgressBar progressBar = (ProgressBar) findViewById(
                                                            R.id.new_module_config_downloadprogress);
                                                    try {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                resetConfigReturned();
                                                            }
                                                        });
                                                        moduleHandler.getNewModule(
                                                                makeModuleCallback(stager, progressBar),
                                                                finalConfig, null, true);
                                                    } catch (IOException e) {
                                                        e.printStackTrace();
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                stager.setText("");
                                                                progressBar.setProgress(0);
                                                            }
                                                        });
                                                        success = false;
                                                    }
                                                    getNewModule.setClickable(true);
                                                    if (refreshAllModification) {
                                                        refreshAll.setClickable(true);
                                                    }
                                                    return success;
                                                } catch (Throwable throwable) {
                                                    throwable.printStackTrace();
                                                    return false;
                                                }
                                            }
                                        });
                                    }
                                });
                                cancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Toast.makeText(MainActivity.this, "Cancelling request...",
                                                Toast.LENGTH_SHORT).show();
                                        resetConfigReturned();
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(MainActivity.this, "Module config invalid. :(",
                                        Toast.LENGTH_LONG).show();
                                layout.setClickable(false);
                                final int colorFrom = ContextCompat.getColor(MainActivity.this,
                                        R.color.colorClear);
                                final int colorTo = ContextCompat.getColor(MainActivity.this,
                                        R.color.colorFillingTint);
                                ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(),
                                        colorFrom, colorTo);
                                colorAnimation.setDuration(ANIMATION_DURATION);
                                colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                    @Override
                                    public void onAnimationUpdate(ValueAnimator animator) {
                                        configResponseBlock
                                                .setBackgroundColor((Integer) animator.getAnimatedValue());
                                    }
                                });
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {
                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {
                        }
                    });
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            colorAnimation.start();
                        }
                    });
                    return true;
                }
            });
        }
    });

    moduleHandler.setup();
    refreshFilling();
    return true;
}

From source file:com.github.nutomic.pegasus.activities.AreaList.java

/**
 * Show an AlertDialog to edit the name of an area.
 * //from ww w  . j  av a 2  s  . c om
 * @param area ID of the area to rename.
 */
private void renameArea(final long id, String name) {
    final Database db = Database.getInstance(this);
    final EditText input = new EditText(this);
    input.setText(name);
    input.setSingleLine();
    AlertDialog alert = new AlertDialog.Builder(this).setTitle(R.string.arealist_rename).setView(input)
            .setPositiveButton(android.R.string.ok, new OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    new UpdateTask() {

                        @Override
                        protected Long doInBackground(Void... params) {
                            // Don't rename default area.
                            if (id != AreaColumns.AREA_DEFAULT) {
                                ContentValues cv = new ContentValues();
                                cv.put(AreaColumns.NAME, input.getText().toString());

                                db.getWritableDatabase().update(AreaColumns.TABLE_NAME, cv,
                                        AreaColumns._ID + " = ?", new String[] { Long.toString(id) });
                            }
                            return null;
                        }
                    }.execute((Void) null);
                }
            }).setNegativeButton(android.R.string.cancel, null).create();
    alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    alert.show();
    input.selectAll();
}

From source file:com.example.android.naradaoffline.DatagramFragment.java

/**
 * Set up the UI and background operations for chat.
 *//*from   w w  w.j  av  a  2 s .com*/
private void setupChat() {
    Log.d(TAG);

    // Initialize the array adapter for the conversation thread
    mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);

    //mConversationView.setAdapter(mConversationArrayAdapter);

    // Initialize the compose field with a listener for the return key
    //        mOutEditText.setOnEditorActionListener(mWriteListener);

    // Initialize the send button with a listener that for click events

    mGetNewsPaper.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Send a message using content of the edit text widget
            View view = getView();
            if (null != view) {

                //                    TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
                DatagramRequest d = new DatagramRequest(DatagramRequestType.GET_NEWSPAPER,
                        mConnectedDeviceName);
                sendDatagramRequest(d);
            }
        }
    });

    // Initialize the send button with a listener that for click events
    mGetEmail.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Send a message using content of the edit text widget
            View view = getView();
            if (null != view) {
                //                    TextView textView = (TextView) view.findViewById(R.id.edit_text_out);

                Log.i(TAG, "button clicked");

                AlertDialog.Builder builder = new AlertDialog.Builder(DatagramFragment.this.getContext());
                builder.setTitle("Write your email here");

                LinearLayout layout = new LinearLayout(getContext());
                layout.setOrientation(LinearLayout.VERTICAL);

                // Set up the input
                final EditText email = new EditText(DatagramFragment.this.getContext());
                email.setHint("Recipient e-mail address");
                // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                layout.addView(email);
                final EditText input = new EditText(DatagramFragment.this.getContext());
                // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
                input.setHint("Type your e-mail here");
                input.setInputType(InputType.TYPE_CLASS_TEXT);
                layout.addView(input);

                builder.setView(layout);
                // Set up the buttons
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mEmail = email.getText().toString();
                        mText = input.getText().toString();
                        DatagramRequest d = new DatagramRequest(DatagramRequestType.SEND_EMAIL,
                                mConnectedDeviceName, "", mEmail, mText);
                        sendDatagramRequest(d);

                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                builder.show();

            }
        }
    });

    // Initialize the BluetoothDatagramService to perform bluetooth connections
    mChatService = new BluetoothDatagramService(getActivity(), mHandler);

    // Initialize the buffer for outgoing messages
    mOutStringBuffer = new StringBuffer("");
}