2016-08-12 18 views
-1

作主語說我正在尋找一種方式來第一次運行,如果上的按鈕,第一次點擊和明年如果點擊該按鈕 跑這裏是我試過Android的 - 運行下一個,如果在第二個按鈕點擊

final Button button = (Button) findViewById(R.id.welcomeButton); 
final TextView textView = (TextView) findViewById(R.id.welcomeText); 
button.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View p1) 
    { 

     int x = 1; 

     if (x == 1) 
     { 
      textView.setText(R.string.step1); 
      button.setText("Next"); 

      // heres increment of the variable x so on next click x will be 2 and the next if will be run instead 
      x++; 
     } 
     if (x == 2) 
     { 
      textView.setText(R.string.step2); 
      button.setText("Next"); 
     } 


    } 
}); 

,你可以看到有關於第一if一個增量,因此增加了變量x,並在下一次按鈕被點擊x爲2和第二個將運行, 但問題是第一個按鈕點擊運行它的第一if然後增加變量並運行下一個if我希望它只能在第一次點擊時先運行。我怎麼能用這種方法做到這一點? 是它更好地使用一個case如果是,請給我它的一個例子提前

+0

問題是你有一個變量,只要你的'onClick'一直存在。這意味着每次點擊按鈕時,都會初始化一個新值爲1的'x',因此您的增量將不起作用 – 0xDEADC0DE

+0

@ 0xDEADC0DE哦。所以這是一個問題。那麼我怎樣才能以另一種方式做到呢?謝謝 。 – NikanDalvand

+1

'if'語句總是'true'。 IDE必須尖叫着你! – Shaishav

回答

0

感謝你需要讓你的x類的成員變量。因此,在你的類的地方,你必須定義它像

private int x = 1; 

,改變你的onClick方法本

@Override 
public void onClick(View p1) 
{ 
    if (x == 1) 
    { 
     textView.setText(R.string.step1); 
     button.setText("Next"); 

     // heres increment of the variable x so on next click x will be 2 and the next if will be run instead 
     x++; 
    } 
    if (x == 2) 
    { 
     textView.setText(R.string.step2); 
     button.setText("Next"); 
    } 
} 

您可能需要重置x地方太

+0

謝謝。它做了這項工作,我也取代了第二,如果與其他如果第一個 – NikanDalvand

0

你把xequal每次用戶點擊按鈕時,

xonClick方法和問題將得到解決!

+0

是的,我發現了我的錯誤上面的答案,我還需要使用其他如果而不是第二個如果。和花花公子不好給-1我即使不是專家每個人都犯錯誤,而學習和編碼:( – NikanDalvand

+0

好吧,我沒有-1 !!我只是編輯你的問題! –

+0

哦好吧,那麼謝謝你的幫助:) – NikanDalvand

0

第1步:你需要做X類否則將永遠被初始化到1的成員變量:

private int x = 1; 

第2步:讓我們來看看代碼。所以x的聲明和初始化可以被刪除。

final Button button = (Button) findViewById(R.id.welcomeButton); 
final TextView textView = (TextView) findViewById(R.id.welcomeText); 
button.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View p1) 
    { 
     //int x = 1; //Now a member variable of the class. 
     if (x == 1) 
     { 
      textView.setText(R.string.step1); 
      button.setText("Next"); 

      // heres increment of the variable x so on next click x will be 2 and the next if will be run instead 
      x++; 
     } 
     else if (x == 2) //if (x == 2) Done so that once it checks the first if it will just move on 
     { 
      textView.setText(R.string.step2); 
      button.setText("Next"); 
     } 
    } 
}); 

我在問題出現的地方旁邊發表了評論。 這就是你使用if而不是其他if。 如果代碼運行時全部檢查條件,無論是否執行了某個if塊。因此,在這種情況下,你會增加,然後程序會檢查下一個,然後是Voila!另一個如果可以執行的塊。

+0

是的,這就是解決方案。上面的兩篇文章也回答了相同的問題,並且在其評論中我說過,如果需要,我需要其他的東西,並且需要將變量放在外面。謝謝回答 :) – NikanDalvand

相關問題