2013-03-25 98 views
0

我有一个TableLyout(在XML文件中),我试图添加表格行。每一行都包含其编号由参数控制的按钮。TableLayout不工作

每次运行此代码时,程序都会退出。它应该是一个简单的任务。出了什么问题?

的Java:

public class Play extends Activity{ 
int status=0 , timeDelay , row , col; 
TextView score; 
TableRow rows []; 
TableLayout table; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.layout_play); 

    setLevel(); 
    table = (TableLayout)findViewById(R.id.Table_cards); 

    for(int i=0 ; i<row ; i++){ 
     TableRow tblr = new TableRow(this); 
     for(int j=0 ; j<col ; j++){ 
      final ImageButton b = new ImageButton(this); 
      b.setOnClickListener(new OnClickListener() { 

       public void onClick(View v) { 
        b.setBackgroundResource(R.drawable.card_back_blue); 
       } 
      }); 
      b.setBackgroundResource(R.drawable.c1+j); 
      tblr.addView(b); 
     } 
     table.addView(tblr); 
    } 
} 

XML文件:

<TableLayout 
    android:id="@+id/Table_cards" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_below="@id/layout_up" 
    android:background="@drawable/wss" 
    android:gravity="center_vertical" 
    android:orientation="vertical" > 
</TableLayout> 
+1

你是否也可以发布'setLevel()'和其他支持的函数以及错误输出。 – Shade 2013-03-25 00:28:22

+0

你需要初始化**行**和** col **变量ex:int row = 5,col = 5; – 2013-03-25 05:00:49

回答

0

此代码工作得很好,

public class Play extends Activity{ 
    private int status=0 , timeDelay , row=10, col=10; 
    private TextView score; 
    private TableRow rows []; 
    private TableLayout table; 
    @Override 
    public void onCreate(Bundle bundle) 
    { 
     super.onCreate(bundle); 
     setContentView(R.layout.table_dynamic); 

//  setLevel(); 
     table = (TableLayout)findViewById(R.id.tableLayout); 

     for(int i=0 ; i<row ; i++){ 
      TableRow tblr = new TableRow(this); 
      for(int j=0 ; j<col ; j++){ 
       final ImageButton b = new ImageButton(this); 
       b.setOnClickListener(new OnClickListener() { 

        public void onClick(View v) { 
//      b.setBackgroundResource(R.drawable.card_back_blue); 
        } 
       }); 
//    b.setBackgroundResource(R.drawable.c1+j); 
       tblr.addView(b); 
      } 
      table.addView(tblr); 
     } 
    } 
} 

和布局table_dynamic,

<TableLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/tableLayout" 
    android:background="@android:color/black" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
</TableLayout> 
+0

你会考虑添加一些叙述来解释为什么这段代码有效吗?是什么使它成为这个问题的答案?这对询问问题的人以及任何其他人来说非常有帮助。 – 2013-03-25 07:08:12

+0

对不起,我会考虑这个。 – 2013-03-25 07:54:13