动态充气给了我一个灵感

时间:2016-04-05 10:13:01

标签: android android-layout nullpointerexception layout-inflater dynamically-generated

我正在使用LinearLayout制作布局。这种布局将在内部膨胀另一种布局。目前,我遇到了问题(nullexceptions)。我的充气代码是下一个:

private void addLayoutInvoices() {

        LinearLayout ll_invoices = new LinearLayout(getActivity());
        ll_invoices.setGravity(Gravity.CENTER);
        ll_invoices.setOrientation(LinearLayout.VERTICAL);

        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        ll_invoices.setLayoutParams(llp);

        ...

        if(mas.size() > 0) {

            for (int i = 0; i < mas.size(); i++) {

                if(mas.get(i).getStatus() == 1){

                    View newGratLayout = LayoutInflater.from(getActivity()).inflate(R.layout.albaran_invoices_row, ll_invoices_layer, false);

                    newGratLayout.setId(i + 8000);

                    RelativeLayout rl_albaran_invoices_row = (RelativeLayout) newGratLayout.findViewById(R.id.rl_albaran_invoices_row);
                    final LinearLayout ll_details = (LinearLayout) newGratLayout.findViewById(R.id.ll_details);

                    ...

                    rl_albaran_invoices_row.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!rowClicked) {
                                ll_details.setVisibility(View.VISIBLE);
                                rowClicked = true;
                            } else {
                                ll_details.setVisibility(View.GONE);
                                rowClicked = false;
                            }
                        }
                    });

                    ll_invoices.addView(newGratLayout);
                }

            }

            ll_invoices_layer.addView(ll_invoices);

            if(existsPending)
                bt_resend_pending.setVisibility(View.VISIBLE);
        }



    }

albaran_invoices_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rl_albaran_invoices_row"
    android:scrollIndicators="none">

    ...

</RelativeLayout>

logcat在行 rl_albaran_invoices_row.setOnClickListener ... 中显示错误NullPointerException。我做错了什么?

注意:我是从片段中做到的。

2 个答案:

答案 0 :(得分:0)

似乎“newGratLayout”视图为null。调试代码,以便获得想法。

答案 1 :(得分:0)

我已更改视图类型以解决问题:

我有......

pack()

现在我有......

//View newGratLayout = LayoutInflater.from(getActivity()).inflate(R.layout.albaran_invoices_row, ll_invoices_layer, false);

感谢人们如何帮助我。