Reputation: 86
Hey There ,I'm totally new to Android ,I actually saw some tutorials and tried it but I still get some errors with my apps *
So I really need to know how to create a simple AlertDialog
when the app starts (With one Positive Button ) and asks "Are you read?" and the button says "Yes", and after clicking yes it shall like the dialog window close and resume the app ..
I tried it but it but my app seems crash and give black screen (It was totally working until adding the Dialog )
So here is The MainActivity Code : *
public class MainActivity extends Activity {
Button w;
TextView t;
EditText e;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
w = (Button) findViewById(R.id.Write);
t= (TextView) findViewById(R.id.FTS);
e = (EditText) findViewById(R.id.Text);
w.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String check1 = t.getText().toString();
String check2 = e.getText().toString();
if (check1.equals(check2))
Toast.makeText(MainActivity.this,"You Wrote it Right !!!",Toast.LENGTH_LONG).show();
else if (check2.equals(""))
Toast.makeText(MainActivity.this,"It's Empty",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"You wrote it wrong,try again !",Toast.LENGTH_LONG).show();
}
Thanks for your time and if there is something I shall add to the Activity_Main.xml with the Dialog
please tell me.
Upvotes: 0
Views: 268
Reputation: 1967
post this code in your Activity
's onCreate()
method:-
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
alertDialogBuilder
.setMessage("Are you read?");
alertDialogBuilder.setPositiveButton(
"Yes"),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//your code here.
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
there's no need for any code to dismiss the dialog as the default implementation will always dismiss the dialog on click on the button.
Upvotes: 1
Reputation: 3830
use this alert box on your oncreate
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
// moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to play This Game?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//start your activiy here
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
}).show();
}
Upvotes: 0