1

我正在创建一个android应用程序,我必须在Android应用程序中显示sqlite的内容。Dynamic TableLayout Android

所以我决定在这里使用TableLayout。但这里的要点是sqlite数据库中的列和行不是先前决定的,所以我需要创建处理动态列和行的那种类型的布局。

所以在这里我在做什么是我创建了一个布局sublayout.xmlcells.xmlmainlayout.xml

sublayout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="horizontal" 
android:id="@+id/subLayout_" > 
</LinearLayout> 

在这种布局中我动态添加使用cells.xml细胞。

cells.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="horizontal" > 

<TextView 
    android:id="@+id/cell_" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Cell" 
    android:textSize="25dp"/> 
</LinearLayout> 

当我一行已经准备好了,我只是把它添加到mainlayout.xml

mainlayout.xml

<?xml version="1.0" encoding="utf-8"?> 

<TableLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <TableRow 
     android:id="@+id/tableRow1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 
     <LinearLayout 
      android:id="@+id/tableLayout_" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"></LinearLayout> 
    </TableRow> 


</TableLayout> 

但我及彼空指针异常。

这是我的班级代码。

LinearLayout layout,subLayout_; 

layout=(LinearLayout)findViewById(R.id.tableLayout_); 
subLayout_=(LinearLayout)findViewById(R.id.subLayout_); 

for (int i = 0; i < columns.length; i++) { 
Log.e("Column name", ""+columns[i]); 
View v=inflater.inflate(R.layout.cells, null); 
TextView tv=(TextView)v.findViewById(R.id.cell_); 
tv.setText(columns[i]); 
subLayout_.addView(v); 
} 

layout.addView(subLayout_); 

请帮我看看我在这里做错了什么?

回答

2

试试这个

layout = (LinearLayout) findViewById(R.id.tableLayout_); 
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View vi = inflater.inflate(R.layout.sublayout, null); 

    subLayout_ = (LinearLayout) vi.findViewById(R.id.subLayout_); 


    for (int i = 0; i < columns.length; i++) { 
     Log.e("Column name", "" + columns[i]); 
     ViewGroup v = (ViewGroup) inflater.inflate(R.layout.cells, null); 
     TextView tv = (TextView) v.findViewById(R.id.cell_); 
     tv.setText(columns[i]); 
     subLayout_.addView(v); 
    } 

    layout.addView(subLayout_); 
1

您可以在这里尝试这种方法。

设计XML这样的:

<TableLayout> 
    <Tablerow> 
    <Add your views here dynamically> 
    </TableRow> 
</TableLayout> 

动态创建textviews,并继续将其添加到的TableRow和最后的TableRow添加到TableLayout。