2017-05-29 59 views
0

我有按鈕的這樣如何在2d按鈕數組上設置onClickListener?

b[1][3] = (Button) findViewById(R.id.uno); 
b[1][2] = (Button) findViewById(R.id.due); 
b[1][1] = (Button) findViewById(R.id.tre); 


b[2][3] = (Button) findViewById(R.id.quattro); 
b[2][2] = (Button) findViewById(R.id.cinque); 
b[2][1] = (Button) findViewById(R.id.sei); 


b[3][3] = (Button) findViewById(R.id.sette); 
b[3][2] = (Button) findViewById(R.id.otto); 
b[3][1] = (Button) findViewById(R.id.nove); 

一個二維數組,我想要得到的東西像

b[x][y].setText("X"); 

我怎麼可以從功能onClickListenerxy

+0

地圖/對/元組的SparseArray .. 。首先在循環中構建它像'sparseArray.append(buttonID,new Pair(x,y))'...然後在onClick中獲得'Pair p = sparseArray.get(view.getId())' – Selvin

+0

爲什麼你無論如何需要索引?如果您可以直接獲取按鈕ID。 –

回答

0

一種解決方案是創建一個自定義監聽器類,然後爲每個新的監聽器實例細胞。

類:

class MyClickListener implements View.OnClickListener { 
    int row; 
    int col; 

    public MyClickListener(int r, int c) { 
     row = r; 
     col = c; 
    } 
    ... 
} 

設置監聽器:

for(int r=0; r<3; r++) 
    for(int c=0; c<3; c++) { 
     screenImages[r][c].setOnClickListener(new MyClickListener(r,c)); 
    } 

然後在課堂上很容易看到哪些行/列按下

0

你可以嘗試先

View view = findViewById(R.id.uno); 
view.setTag(1+""+3); 
b[1][3] = view; 

,然後在的onClick

String s = v.getTag().toString(); 
int y = Integer.parseInt(TAG.substring(1)); 
int x = Integer.parseInt(TAG.substring(0,1)); 
我用
0
b[1][3] = (Button) findViewById(R.id.uno); 
b[1][3].setTag("1#3"); 

b[1][3].setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     String tag = (String) v.getTag(); 
     int x = tag.split("#")[0]; // 1 
     int y = tag.split("#")[1]; // 3 
    } 
}); 
相關問題