2012-04-16 46 views
1

我正在嘗試編寫一個簡單的棒球記分應用程序,主要是作爲一個學習練習。Android:基於一個對象的onClick操作多個(按鈕)對象

在這一點上,我有一個功能齊全的應用程序。它有一個活動和一個佈局。所有的數字(球,罷工,出局,局)都顯示爲按鈕。我已經擴展了android.widget.Button類,以便按鈕的文本是一個整數,並且在單擊按鈕時使用onClick將值遞增1。該對象還存儲最大值;當增量達到該值時,計數器重置爲0.因此,例如「球」按鈕的最大值爲4,並計數0,1,2和3.當您下一次從3 (對那些不知道或關心棒球的人道歉)。

所有這些工作都很好,就像它一樣(我的擴展按鈕類的源代碼如下所示)。現在,我試圖改變它,以便當一個計數器回到0時,其他人也會這樣做。我對如何做到這一點感到不知所措。我的第一反應是,只是在添加到同一個「如果」語句翻轉值回0,像這樣:

final ScoreButton strikes = (ScoreButton) findViewById(R.id.strikes); 
strikes.zero(); 

(其中「罷工」是在活動中定義的ScoreButton對象)。這返回一個空指針錯誤。

我的第二個想法是添加一個布爾屬性,增量方法可以設置它何時回到0(「重置」)。但我不明白在哪裏閱讀這個屬性。我可以在onResume方法中檢查一次,但嘗試像「while」循環那樣重複讀取變量,只是鎖定應用程序而不顯示主佈局。

試圖研究一個更好的方法來做到這一點,導致我閱讀關於AsyncTask,這似乎是矯枉過正,我不知道它甚至會工作,因爲任務(即檢查是否已經重置一個特定的按鈕)並沒有結束。

在這一點上,這似乎是這麼簡單,我一定錯過了一些明顯的東西。我會很感激你的任何建議。

代碼爲我的自定義按鈕:

import android.widget.Button; 
import android.content.Context; 
import android.view.View; 
import android.util.AttributeSet; 

public class ScoreButton extends Button { 

protected int flipCount; 
protected int currCount; 
protected boolean reset; 

public ScoreButton(Context context) { 
     super(context); 
    } 

public ScoreButton(Context context, AttributeSet attr) { 
     super(context, attr); 
     setOnClickListener(incr); 
     setOnLongClickListener(dec); 
} 

public void init(int start, int max) { 
    flipCount = max; /** number at which the counter goes back to 0 **/ 
    currCount = start; /** number to start at **/ 
    reset = false; 
    setText(Integer.toString(currCount)); 
} 

/** reset the button value to 0 **/ 
public void zero() { 
    currCount = 0; 
    setText(Integer.toString(currCount)); 
} 


private OnClickListener incr = new OnClickListener() { 
    public void onClick(View v) { 
    currCount++; /** increment number on button **/ 
    if (currCount == flipCount) { /** if at the maximum value, go back to 0 **/ 
     currCount = 0; 
     reset = true; 
     final ScoreButton strikes = (ScoreButton) findViewById(R.id.strikes); 
     strikes.zero(); 
     } 
    setText(Integer.toString(currCount)); /** display the new button text **/ 

    } 
} ; 

/** this method decreases the value by 1 on a long click **/ 
private OnLongClickListener dec = new OnLongClickListener() { 
    public boolean onLongClick(View v) { 
    currCount--; 
    if (currCount == -1) { 
     currCount=0; 
    } 
    setText(Integer.toString(currCount)); 
    return true; 
} 
} ; 
} 

回答

0

你是正確的,以不嘗試你所描述的方法AsynkTask。這是不正確的。

這裏是我的建議: 你可以給所有的ScoreButton個更復雜的onClickListener,你會在你的Activity定義(從活動的範圍,而不是ScoreButton類的範圍)。這將是一個包含所有Button s成員變量信息的監聽器。您只能創建一個實例,但將其傳遞給所有ScoreButton s [或Button s到setOnClickListener()。當其中一個分數需要打包時,只需將Listener中的所有其他計數器設置爲0. [注意:在這種方法中,即使可以,您甚至不需要繼承子類Button]。

但是,既然你說你在學習,你甚至可以嘗試創建一個你可以放在你的視圖層次結構中的ScoreButtonGroupView。這將是一個很好的自包含解決方案,它具有適當地設置按鈕值的內部邏輯(正如我認爲你通過繼承子類Button所做的那樣)。

+0

謝謝,我沒有想到我可以爲所有按鈕定義一個通用的onClick處理程序。我會去做。團體觀點是一個有吸引力的想法,但我想我會留下它的未來版本。 – grasshopper 2012-04-16 16:13:24