Android UI How to - Use AlertDialog to display text from EditText








The following code shows how to use AlertDialog to display text from EditText.

Example

/*from   ww w  .  jav  a2 s.  co m*/

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/script"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/eval"
        android:test="OK"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

Java code

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/*w  ww  .java 2s.c om*/
public class MainActivity extends Activity {
  
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    Button btn=(Button)findViewById(R.id.eval);
    final EditText script=(EditText)findViewById(R.id.script);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        String src=script.getText().toString();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Exception!")
             .setMessage(e.toString())
            .setPositiveButton("OK", null)
            .show();
      }
    });
  }
}
null