2011-07-01 29 views
0

所以我創建這個android應用程序讀取文件。我想要的一個功能是允許用戶輸入頁碼,然後讓應用打開該特定的頁碼。由於我是Android新手,我在網上查找了一些信息,並找到了一些關於Edittext和AlertDialog的信息。在我的代碼中,如果用戶打開菜單並點擊「轉到」,則AlertDialog會打開,要求用戶輸入頁碼。我將該字符串轉換爲一個int,然後該應用程序應該跳轉到該頁面。但是,由於某些奇怪的原因,如果用戶從菜單再次點擊GO TO,它只會跳轉到指定的頁面。我很困惑,爲什麼用戶必須再次按GO TO來執行指定的操作。Android應用程序使用AlertDialog提示用戶輸入頁碼和應用程​​序,然後跳轉到該頁

 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 not parse " + nfe); 
      } 

      // Do something with value! 
     } 
     }); 

     alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
      // Canceled. 
      } 
     }); 
     alert.show(); 
     c = -1; 

對於這段代碼,我設置了一個try/catch塊來啓動函數。基本上,當從菜單點擊GO TO時,變量c變爲-1,然後我有一個if語句,只有在c = -1時才跳轉到第N頁。

我只是不明白,爲什麼在AlertDialog打開並且用戶輸入一個數字後c沒有設置爲-1。爲什麼在用戶再次點擊GO TO後必須設置爲-1。謝謝!

+0

經過更多的測試後,我覺得它與AlertDialog的性質有關,有沒有其他的東西可以用來代替AlertDialog? – KfC

回答

1

我會做的是在肯定按鈕(Ok)的onClick處理程序中,一旦設置了num,將該數字發送到跳轉到第n頁的方法。所以像這樣的事情:

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 
    } 
相關問題