簡體   English   中英

如何使用.xml在Android中的TableLayout中動態添加TableRow?

[英]How to add dynamicaly TableRow inside a TableLayout in Android using .xml?

我在TableLayout內添加帶有TextView的行時遇到問題。

我創建了一個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)

如果有人對此感興趣,這就是解決我的問題的方法。

我用了:

private LayoutInflater inflater;
View tr = inflater.inflate(R.layout.table_row_chronology, null);

代替:

LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

下面是代碼:

private LayoutInflater inflater;
View tr = inflater.inflate(R.layout.table_row_chronology, null);
TableLayout tableChronology = (TableLayout) findViewById(R.id.mainTable);
tableChronology.addView(tr);

您應該編寫以下代碼以使其正常工作

private TableLayout tableChronology = (TableLayout) findViewById(R.id.tableLayout1);
TableRow tablerow = new TableRow(this);
View tr = inflater.inflate(R.layout.table_row_chronology, tablerow, false);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM