单击按钮时将TableRow xml布局添加到TableLayout

时间:2017-01-10 14:55:06

标签: android xml android-layout

我有一个布局xml文件,当用户单击按钮时,我试图将其附加到TableLayout。这是我的onClick监听器方法:

addHazardButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        TableLayout table = (TableLayout) view.findViewById(R.id.safety_question_table);
        View row = getLayoutInflater(null).inflate(R.layout.fragment_safety_question_table_row, table);
        table.addView(row);
    }
});

我还尝试使用以下内容替换行View row = getLayoutInflater....

View row = getLayoutInflater(null).inflate(R.layout.fragment_safety_question_table_row, null);,
&
TableRow row = getLayoutInflater(null).inflate(R.layout.fragment_safety_question_table_row, table);,
&
TableRow row = getLayoutInflater(null).inflate(R.layout.fragment_safety_question_table_row, null);

我也尝试将layoutInflater从onCreateView方法传递给我的onClickListener设置并使用它的方法,但我不认为这是问题,因为堆栈跟踪是

  

java.lang.NullPointerException:尝试调用虚方法' void   android.widget.TableLayout.addView(android.view.View)'在null   对象参考

如何将我的xml布局文件正确添加到onClick?

表中
<?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="wrap_content">

<EditText
    android:id="@+id/task_step_text"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_weight="1"
    android:background="@drawable/border_outline"
    android:inputType="text"
    android:maxLines="1" />

<EditText
    android:id="@+id/hazards_not_covered_text"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_weight="1"
    android:background="@drawable/border_outline"
    android:inputType="text"
    android:maxLines="1" />

<EditText
    android:id="@+id/reduce_risk_text"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_weight="1"
    android:background="@drawable/border_outline"
    android:inputType="text"
    android:maxLines="1" />
</TableRow>

1 个答案:

答案 0 :(得分:1)

使用

TableLayout table = (TableLayout) findViewById(R.id.safety_question_table);

而不是

TableLayout table = (TableLayout) view.findViewById(R.id.safety_question_table);

因为TableLayout可能位于“活动”布局中而不是“按钮视图”中。

OR

如果TableLayout位于Button的父视图中,那么我们也可以将其视为:

    View parent = (View)view.getParent();
    if (parent != null) {
        TableLayout table = 
           (TableLayout)parent.findViewById(R.id.safety_question_table);
        // add your code here
    }
相关问题