so I'm creating this android app that reads files. One feature that I want is to allow the user to enter a page number and then have the app open up that specific page number. Because I'm new to Android, I looked up some information online and found some information regarding Edittext and AlertDialog. In my code, if the User opens the menu and hits "Go To" then an AlertDialog opens asking the user to enter a page number. I convert that string into an int, and then the app SHOULD jump to that page. However, for some odd reason, it only jumps to the specified page if the user hits GO TO again from the menu. I'm confused as to why the user has to hit GO TO again for the specified action to take place.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Go to page number...");
alert.setMessage("Enter page number:");
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
num = Integer.parseInt(input.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could no开发者_开发知识库t parse " + nfe);
}
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
c = -1;
For this code, I set up a try/catch block to initiate the function. Basically when hitting GO TO from the menu, the variable c becomes equal to -1, I then have an if statement that performs the jump to Nth page only if c = -1.
I just don't get why c isn't set to -1 right after the AlertDialog opens and the user enters a number. Why must it be set to -1 after the user clicks GO TO one more time. Thanks!
What I would do is in the onClick handler for the positive button (Ok), once the num is set, send that number to a method that jumps to the nth page. So something like this:
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
num = Integer.parseInt(input.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
jumpToPage(num);
}
});
public void jumpToPage(num) {
// jump to page
}
精彩评论