我無法在TableLayout中使用TextView添加行。如何在Android的TableLayout中使用.xml添加dynamicaly TableRow?
我創建了一個table_row.xml,其中我通過xml定義了我的TableRow及其TextView的。
table_row XML:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="@string/food_label"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView_kcal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/kcal_label"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
這裏是我做什麼:
內部類,我想給它充氣在 我定義
LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private TableLayout tableChronology = (TableLayout) findViewById(R.id.tableLayout1);
View tr = inflater.inflate(R.layout.table_row_chronology, null,false);
// Here is where i get an error;
tableChronology.addView(tr);
這裏是logcat的:
FATAL EXCEPTION: main
Process: com.example.appscan5, PID: 31647
java.lang.NullPointerException
at com.example.appscan5.Today$2.onClick(Today.java:66)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
看來你沒有一個元素'R.id.tableLayout1'在你的主視圖中。發佈完整的代碼以更好地理解問題。 – cosmincalistru
用主佈局發佈XML,好像'tableLayout1'缺少那裏 – nikis