2017-03-07 75 views
2

儘管這看起來有很多重複的問題,但第一次對我來說。我搜遍了,無法得到結果,並最終張貼在這裏。將TableRow動態添加到xml的TableLayout中

我正在創建一個動態表,其中TableLayout部分是用xml部分編寫的。

<RelativeLayout 
     android:layout_width="70dp" 
     android:layout_height="40dp" 
     android:background="@color/colorPrimaryDark" 
     android:id="@+id/componentA"> 
     <TableLayout 
      android:layout_width="match_parent" 
      android:layout_height="40dp" 
      android:gravity="center" 
      android:id="@+id/tl_componentA"> 


     </TableLayout> 

</RelativeLayout> 

我創建了一個對象表

TableLayout tableLayoutA; 
tableLayoutA= (TableLayout)view.findViewById(R.id.tl_componentA); 

現在我試圖從這裏開始動態添加行作爲

createTableRowColumn(tableLayoutA); 

功能相關的

private void createTableRowColumn(TableLayout tableLayout){ 

     TableRow tableRow1= new TableRow(this.context); 
     tableRow1.setBackgroundColor(getResources().getColor(R.color.colorAccent)); 
     setTableRowColumnProperty(tableRow1); 
     tableLayout.addView(tableRow1); 
    } 

私人無效setTa bleRowColumnProperty(的TableRow tablerow的){

TableRow.LayoutParams layoutParams= new TableRow.LayoutParams(70, 40); 
    tableRow.setLayoutParams(layoutParams); 
} 

我做了這一切,並沒有表現出我的emulater。但是,當我手動給xml賦予相同的結構時,事情運作良好。

出於這個原因,我試過的東西弄清楚

Toast.makeText(getContext(), tableLayoutA.getHeight()+"", Toast.LENGTH_LONG).show(); 

在祝酒它向我展示0.我不知道爲什麼,雖然我已經在XML本身固定tableLayoutA大小。

+0

請你詳細說明一下嗎? –

+0

無論如何,我通過動態理解,當數據在TableLayout中不斷變化時,是你想說的是什麼?或者 –

+0

你能否糾正這些代碼併發布,以便我可以知道我在哪裏做錯了? –

回答

2

現實生活中的表格至少需要一行一列。 您沒有看到表格,因爲您只創建了一行,但沒有列。

您需要在行中添加一列以顯示某些內容。

試試這個:

TextView label_date = new TextView(this); 
    label_date.setText("DATE"); 
    label_date.setTextColor(Color.WHITE); 
    label_date.setPadding(5, 5, 5, 5); 
    tableRow.addView(label_date);// add the column to the table row here 

    tableLayout.addView(tableRow, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

您可以替換任何價值,你希望它是TextView的。

tableLayout.addView(tableRow, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

這裏發生的事情是,你說,添加視圖到tableLayout,你知道哪些瀏覽它,你也說視圖的寬度和高度應該把它包裝的內容。

此外,指定40,70不是一個好主意,當屏幕大小變化時會發生什麼。此外,使用庫來處理動態視圖添加和刪除。您不需要重新發明輪子並節省大量時間和精力。對於表格視圖,https://github.com/EsotericSoftware/tablelayout可能是一個很好的(不確定)。另一個問題是,表格查看你在找什麼?確保你沒有把recyclerView誤認爲表格視圖,我這樣說是因爲我不明白你的用例。

有用的鏈接:https://technotzz.wordpress.com/2011/11/04/android-dynamically-add-rows-to-table-layout/

+0

多數民衆贊成在工作。你能否向我解釋發生了什麼事。另請解釋如何工作--- tableLayout.addView(tableRow,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); –

+0

如果您發現我的回答有用,請投票選擇 – rgv

+0

爲什麼不使用TableRow.LayoutParams? –