在对话框中设置分隔线

时间:2019-02-18 06:38:58

标签: java android nullpointerexception

我想在dialog中设置分隔线
我这样做:

   if (dialog != null) {
        final int dividerId = dialog.getContext().getResources()
                .getIdentifier("android:id/titleDivider", null, null);
        View divider = dialog.findViewById(dividerId);
        if  (divider != null) {
            divider.setBackground(null);
        }

这是我的整个代码:

  public void setParamsDialog(String componentName, String componentCode, String unit) {
        dialog.setContentView(R.layout.dialog_consumables);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        dialog.setCancelable(false);
        dialog.show();

        if (dialog != null) {
            final int dividerId = dialog.getContext().getResources()
                    .getIdentifier("android:id/titleDivider", null, null);
            View divider = dialog.findViewById(dividerId);
            if (divider != null) {
                divider.setBackground(null);
            }
        }
        int titleDividerId = dialog.getContext().getResources().getIdentifier("titleDivider", "id", context.getPackageName());
        dialog.getWindow().getDecorView().findViewById(titleDividerId).setVisibility(View.GONE);

        compNameText = (TextView) dialog.findViewById(R.id.component_name);
        compCodeText = (TextView) dialog.findViewById(R.id.component_code);
        compUnitText = (TextView) dialog.findViewById(R.id.amount_unit);
        searchEditText = (EditText) dialog.findViewById(R.id.search);
        amountEditText = (EditText) dialog.findViewById(R.id.edittext_amount);

        mListView = (ListView) dialog.findViewById(R.id.consumables_list);
        searchConsumables = (RelativeLayout) dialog.findViewById(R.id.search_consumables);

        cancelButton = (Button) dialog.findViewById(R.id.negative_btn);
        saveButton = (Button) dialog.findViewById(R.id.positive_btn);

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
    }

但是在android API 23上,我得到了一个空指针

logcat日志:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
        at pl.dialog.box.DialogConsumables.setParamsDialog(DialogConsumables.java:85)
        at pl.barcode.readers.BarcodeReader$2.onClick(BarcodeReader.java:198)

1 个答案:

答案 0 :(得分:0)

根据错误日志

  

尝试调用虚拟方法'void   空对象引用上的android.view.View.setVisibility(int)'

它指向

dialog.getWindow().getDecorView().findViewById(titleDividerId).setVisibility(View.GONE);

所以我建议您像这样在dialog_consumables内设置分隔线

<ListView
        android:id="@+id/consumables_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="2dp" >