2016-07-04 40 views
0

考慮這個下面的代碼:如何從OnClick方法擺脫對按鈕偵聽Android中

Button add_product_button = (Button) findViewById(R.id.add_product_button); 
    add_product_button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      //Before going further, we check whether all the information is provided or not 
      EditText item_title_text = (EditText) findViewById(R.id.item_title); 
      if(isEmpty(item_title_text)){ 
       break; 
      } 

我想要的「突破;」作爲我不想進一步處理的迴應(不執行其他代碼,只是退出)。

這是警告用戶沒有提供足夠的信息。我怎樣才能做到這一點?

回答

1

我真的建議禁用您的按鈕,如果需要的信息是不存在的,因此用戶不能點擊它。您可以在任何對話框/視圖上顯示消息以通知用戶需要信息,或者在EditText提示之後添加一個字符串,如「(必填)」。

Button add_product_button = (Button) findViewById(R.id.add_product_button); 
EditText item_title_text = (EditText) findViewById(R.id.item_title); 

if(isEmpty(item_title_text)){ 
    add_product_button.setEnabled(false); 
} 

然而,如果你需要做它,你出於某種原因所描述的方式,回答你如何「走出」,你只需要return出的onClick方法。

if(isEmpty(item_title_text)){ 
    return; 
} 

返回你可以調用一些方法,做任何你想做的事之前,(你自己的方法,也許會顯示一個消息,他們沒有足夠的信息的用戶)。

if(isEmpty(item_title_text)){ 
    notifyUserOfEmptyField(); 
    return; 
} 
+0

是它返回; ;我已經忘記了它。 – user3787757

0

要擺脫它不與代碼事情只是

if(isEmpty(item_title_text)){ 
    return; 
} 

你可能想顯示吐司與在那裏的錯誤:

if(isEmpty(item_title_text)){ 
    Toast.makeText(...); 
    return; 
}