android.widget.TableRow无法强制转换为android.widget.TableLayout

时间:2014-01-23 18:12:01

标签: android android-layout exception

我编写了我的第一个Android应用程序,简单的CRUD。但在我将GridView更改为TableLayout后,我收到以下错误:

android.widget.TableRow cannot be cast to android.widget.TableLayout

这是我的活动:

public class AllActivity extends Activity {

    private SQLiteDatabase sampleDB;
    private TableLayout tableList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all);





        sampleDB = this.openOrCreateDatabase("my_app",
                SQLiteDatabase.CREATE_IF_NECESSARY, null);


        String query = "SELECT * FROM BOOKS;";
        Cursor cursor = sampleDB.rawQuery(query, null);


        tableList = (TableLayout)findViewById(R.id.tableList);

        if(cursor.moveToFirst())
        {
            do
            {
                TableRow row = new TableRow(this);

                TextView id = new TextView(this);
                id.setText(""+cursor.getLong(0));

                TextView title = new TextView(this);
                title.setText(cursor.getString(1));

                TextView author = new TextView(this);
                author.setText(cursor.getString(2));


                row.addView(id);
                row.addView(title);
                row.addView(author);

                tableList.addView(row);



            }while(cursor.moveToNext());

        }

    }


}

我的观点:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TableRow
        android:id="@+id/tableList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TableRow>

</LinearLayout>

任何提示我做错了什么? 我做了Print out ArrayList content in Android TableLayout之类的所有事情,但无法让它发挥作用。

1 个答案:

答案 0 :(得分:2)

android.widget.TableRow cannot be cast to android.widget.TableLayout

你有

 <TableRow
    android:id="@+id/tableList" // table row
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</TableRow>

但在初始化时你已经

 tableList = (TableLayout)findViewById(R.id.tableList);
 // casting tablerow to tablelayout

您可以查看

http://www.mkyong.com/android/android-tablelayout-example/

您还可以在sdk samples @

中找到表格布局的示例

Android的SDK /样品/机器人-17 / ApiDemos / RES /布局/ table_layout_1.xml