在Tablelayout中显示数据时出现问题

时间:2011-07-13 06:42:02

标签: android

我使用了TableLayout来显示数据。数据采用json格式,因此我创建了带有填充数据的动态TableRow和TextView,并将其放入TableLayout。在测试应用程序中,我已经使用了一个修复字符串数组来填充表格来代替json。没关系。

问题是所有代码运行良好且没有错误。即使我已调试每行代码。我没有发现任何错误。事件然后我的数据没有显示在表格中。 TableLayout在启动时保持空白。 我的代码是:

    @Override
public void onCreate(Bundle savedInstanceState) {
    try
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabular_layout);        
        final TableLayout tl = (TableLayout)findViewById(R.id.tblLyt);

        for(int i = 0; i<names.length; i++)
        {

            TableRow tr = new TableRow(this);               
            TextView tv1 = new TextView(this);
            TextView tv2 = new TextView(this);

            createView(tr, tv1, Integer.toString(i+1));
            createView(tr, tv2, names[i]);

            tl.addView(tr);             
        }

    }
    catch(Exception ex)
    {
        MessageBox(ex.getMessage());
    }
}

public void createView(TableRow tr, TextView t, String viewdata) throws Exception{
    try
    {
        t.setText(viewdata);
        t.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        t.setTextColor(Color.DKGRAY);
        t.setBackgroundColor(Color.WHITE);
        t.setPadding(20, 0, 0, 0);
        tr.setPadding(0, 1, 0, 1);
        tr.addView(t); // add TextView to row.
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

这是我的tabular_layout.xml文件。

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent" android:weightSum="1">
       <TableLayout android:layout_width="fill_parent" android:id="@+id/tblLyt"       android:layout_height="wrap_content" android:layout_weight="0.69">             
       </TableLayout>

   </LinearLayout>

我还是Android新手。我可能会犯愚蠢的错误。但是我在这方面做了很多尝试,并且还在搜索它。 所以帮助我!!

感谢。

2 个答案:

答案 0 :(得分:1)

问题出现在以下行中。阻止它并运行程序

t.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

答案 1 :(得分:0)

/ ** *您需要返回tablerow并保持在mainlayout中。  使用下面的代码 /

public TableRow createView(TableRow tr,TextView t,String viewdata)抛出Exception {     尝试     {         t.setText(可视数据);         t.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));         t.setTextColor(Color.DKGRAY);         t.setBackgroundColor(Color.WHITE);         t.setPadding(20,0,0,0);         tr.setPadding(0,1,0,1);         tr.addView(T); //将TextView添加到行。     }     catch(Exception ex)     {         抛出前     }

retuen tr; }

//调用像dynamica布局 tl.addView(createView(tr,tv1,Integer.toString(i + 1));