2011-08-20 64 views
4

我的問題有三個部分。減少Button onClick事件的代碼

我的佈局由26個按鈕:按鈕a,ButtonB,ButtonC ... ButtonZ

的按鈕依次排列在屏幕上。當點擊按鈕時,我想要捕獲單擊事件並通過單擊的第一個字母過濾SQLiteDB的單詞。

如何編寫能夠捕獲點擊,識別按鈕的相應字母並返回以SQLite數據庫中所選字母開頭的字母的最小數量的代碼?

下面是我的代碼沒有被優化的代碼簡潔。

//Create your buttons and set their onClickListener to "this" 
    Button b1 = (Button) findViewById(R.id.Button04); 
    b1.setOnClickListener(this); 

    Button b2 = (Button) findViewById(R.id.Button03); 
    b2.setOnClickListener(this); 


    //implement the onClick method here 
public void onClick(View v) { 
    // Perform action on click 
    switch(v.getId()) { 
    case R.id.Button04: 
     //Toast.makeText(this,"test a",Toast.LENGTH_LONG).show(); 

    // Do the SqlSelect and Listview statement for words that begin with "A" or "a" here. 

     break; 
    case R.id.Button03: 
     //Toast.makeText(this,"test b",Toast.LENGTH_LONG).show(); 

// Do the SqlSelect and Listview statement for words that begin with "A" or "a" here. 
     break; 
    } 

}

回答

2

如果每個字符都有很多字符和一個按鈕,我可能會擴展「BaseAdapter」類並使ButtonAdapter將字母表作爲字符數組,而不是實際製作28:ish按鈕...。 ..如果我正確理解問題?

的getView可能是這個樣子:

public View getView(int position, View convertView, ViewGroup parent) { 
    Button button; 

    if (convertView == null) { 
     button = new Button(mContext); 
     button.setTag(alphabet[position]); 
     button.setOnClickListener(clickListener); 
    } else { 
     button = (Button) convertView; 
    } 

    button.setText(alphabet[position]); 
    return button; 
    } 
0

如果你的佈局在XML定義,您可能需要使用參數爲您的按鈕。這樣您可以保存findViewById()setOnClickListener()的呼叫。

0

由於alextsc說,如果你願意,你減少你的活動代碼,您可以綁定從XML點擊聽衆。但是,我認爲在給定其性質的循環內的代碼中定義按鈕可能更好。只需在佈局中創建一個簡單的容器(例如LinearLayout)並添加到按鈕即可。我們可以利用這一點,你可以遍歷字符(對待他們像整數)的事實,像這樣:

for (char letter = 'a'; letter <= 'z'; letter++) { 
    Button button = new Button(this); 
    button.setText(String.valueOf(letter)); 
    button.setOnClickListener(this); 
    container.addView(button); 
} 

至於你的實際點擊監聽器,你並不真的需要打開自己的ID,以你想要做什麼。你知道按鈕的數據只是它們的文本值。只需提取並以統一的方式使用它:

public void onClick(View v) { 
     Button button = (Button) v; 
     String letter = button.getText().toString(); 
     // filter using letter 
} 
+0

感謝安東,Alex和馬爾科,我用「的onClick」作爲XML的一部分,而「公共無效的onClick(視圖v)」代碼。它真的清理了一個活動。再次感謝指針,mucho讚賞 –