2012-07-04 60 views
1

我製作了自己的複合控件,它使用TableLayout顯示數據網格,並以編程方式在循環內添加Tablerows,取決於綁定到它的Object對象Array,現在我想選擇特定的行與其特定的數據以供方法使用。那麼如何選擇檢索其數據的特定行來委託方法?如何點擊TableLayout中的特定TableRow

+0

我有同樣的問題,但我想上的TableRow使用onItemClickListener,因爲我想知道按下了哪個列。無法找到如何將TableRow轉換爲女巫支持onItemClick的方式。有沒有解決方法? –

回答

7

嗨,你可以嘗試這樣的事情,

// create a new TableRow 

    TableRow row = new TableRow(this); 
    row.setClickable(true); //allows you to select a specific row 

    row.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      v.setBackgroundColor(Color.GRAY); 
      System.out.println("Row clicked: " + v.getId()); 

      //get the data you need 
      TableRow tablerow = (TableRow)v.getParent(); 
      TextView sample = (TextView) tablerow.getChildAt(2); 
      String result=sample.getText().toString(); 
     } 
    }); 

欲瞭解更多信息請參閱Android TableRow

5

我試圖PARTH多希的答案,並發現它是不完全正確的。 onClick中的view參數爲TableRow,因此調用v.getParent()時,它將返回一個TableLayout對象,因此在將其轉換爲TableRow時會引發異常。至於這樣對我的作品的代碼是:

tableRow.setClickable(true); //allows you to select a specific row 

tableRow.setOnClickListener(new OnClickListener() { 
     public void onClick(View view) { 
     TableRow tablerow = (TableRow) view; 
     TextView sample = (TextView) tablerow.getChildAt(1); 
     String result=sample.getText().toString(); 

     Toast toast = Toast.makeText(myActivity, result, Toast.LENGTH_LONG); 
     toast.show(); 
    } 
}); 
+0

謝謝!那肯定比標記的答案更好 – driftwood

相關問題