2011-11-05 96 views
1

我已經創建了一個來自sqllite數據庫的動態按鈕陣列。對於我的生活,我無法獲得一個點擊偵聽器來設置每個按鈕的單獨地址。我一直在尋找3個小時,但沒有成功。如何獲取onClickListener Android按鈕陣列

任何幫助,將不勝感激。不要擔心數據庫垃圾,它只是聽者。

imports... 

public class CreatePlayList extends Activity { 

    ScrollView scrollleft, scrollright; 
    LinearLayout songsright, songsleft; 
    TextView testtext; 
    String[][] allsongs; 
    int numofsongs, i; 
    Button b1[]; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.createplaylist); 
     scrollleft = (ScrollView) findViewById(R.id.scrollleft); 
     scrollright = (ScrollView) findViewById(R.id.scrollright); 
     songsright = (LinearLayout) findViewById(R.id.layRight); 
     songsleft = (LinearLayout) findViewById(R.id.layLeft); 
     LyricDb connect = new LyricDb(CreatePlayList.this); 
     connect.open(); 
     numofsongs = connect.getNumSongs(); 
     b1 = new Button[(numofsongs)]; 
     allsongs = new String[numofsongs][2]; 
     allsongs = connect.getSongArray(); 
     connect.close(); 
     testtext = new TextView(this); 
     testtext.setText("Test"); 
     songsleft.addView(testtext); 

     for (i = 0; i < allsongs.length; i++) { 
      b1[i] = new Button(this); 
      b1[i].setText(allsongs[i][1]); 
      songsright.addView(b1[i]); 
     } 

     b1[19].setText("test 123"); 
     createClic(); 
    } 

    public void createClic(){ 
     for (i = 0; i < (allsongs.length - 1); i++) { 
      b1[i].setOnClickListener(new View.OnClickListener() { 

       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        testtext.setText(b1[i].getText()); 
       } 
      }); 
     } 
    } 
} 
+0

那麼,有什麼問題?你是否收到某種錯誤信息?是否有任何機會不讓你在onClick方法中引用b1? –

回答

2

垃圾堆裏的 'I' 在類級別聲明。用這個替換方法(「Button theButton」需要保持'最終')。

public void createClic() 
{ 
    for (int i = 0; i < (allsongs.length - 1); i++) 
    { 
     final Button theButton = b1[i]; 
     theButton.setOnClickListener(new View.OnClickListener() 
     { 

      public void onClick(View v) 
      { 
       // TODO Auto-generated method stub 
       testtext.setText(theButton.getText()); 
      } 
     }); 
    } 
} 
+0

謝謝凱文,做到了。 – NJGUY

0

嘗試一次...

b1[i] = new Button[allsongs.length]; 
    for (i = 0; i < allsongs.length; i++) { 

     b1[i].setText(allsongs[i][1]); 
     songsright.addView(b1[i]); 
    } 
1

首先在您的Activity中實現OnClickListener,並在創建它時調用setOnClickListener()方法到所有按鈕。

b[i].setOnClickListener(this); 
and also set id with each button 
b[i].setId(i); 

//and override this method 
@Override 
public void onClick(View v) 
{ 
    //here check which button called 
    if(v.getId==1) 
    { 
     //its Button 1 do what ever u want  
    } 
    if(v.getId==2) 
    { 
     //its Button 2 do what ever u want its Button 2 
    } 
    ...... 
}