以编程方式将“表布局”设置为content_main.xml



我是安卓开发的新手,通过开发看起来容易但不起作用的UI来解决问题。我有一个应用程序的方法,它应该为我建立一个新的UI

它应该创建一个包含 x 个表行的tableLayout。我不知道以前有多少,所以我在代码中这样做。但我什么也没看到,也没有收到任何错误/警告。

这是我来自MainActivity的代码.java

private void buildNewUI(PatientRepository repoPatient, ExternalSystemsRepository repoExtSys){
    TableLayout tableLayout = new TableLayout(this);
    tableLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
    tableLayout.setStretchAllColumns(true);
    Iterator patIterator = repoPatient.getIterator();
    while(patIterator.hasNext()){
        TableRow row = new TableRow(this);
        Patient patient = (Patient) patIterator.next();
        TextView outputLeft = new TextView(this);
        outputLeft.setText(patient.getSurname());
        row.addView(outputLeft);
        tableLayout.addView(row);
    }
}

Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.patientfinder.MainActivity">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
    <include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>

and content_main.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.patientfinder.MainActivity"
    tools:showIn="@layout/activity_main">
</TableLayout>

我的错误是什么?

对不起!有时你会在一分钟后找到解决方案...

我在context_main.xml中为我的 TableLayout 提供了 id TableLayout,然后在代码中,我将创建新表布局替换为:

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

现在它工作了,我看到了我的桌子!

最新更新