【问题标题】:android setOnClickListener gives null pointer exception?android setOnClickListener 给出空指针异常?
【发布时间】:2010-11-01 12:08:49
【问题描述】:

我已经为另一个视图顶部的自定义对话框的onClick 方法编写了代码。它给了我nullpointer exception。我也尝试过使用 Layout inflater。它给了我ok.setOnclickListener 的错误。我的代码有什么问题?

 ImageButton search =(ImageButton) findViewById(R.id.search);
            search.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    Dialog searchDialog = new Dialog(Page.this);

                    /*LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


                     View layout = inflater.inflate(R.layout.search, null);
                     searchDialog.addContentView(layout, new LayoutParams(
                                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                     searchDialog.setContentView(layout);*/

                    searchDialog.setContentView(R.layout.search);
                    searchDialog.setTitle("Search Dialog");
                    searchDialog.setCancelable(true);

                    Button ok = (Button)findViewById(R.id.OkButton);
                    ok.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            String searchString = null;
                            EditText searchText = (EditText)findViewById(R.id.searchText);
                            if(searchText.getText()!=null){
                                searchString = searchText.getText().toString();
                            }
                            Log.i("TAG","Search word :"+searchString);

                        }
                    });

                    searchDialog.show();



                }


            });

【问题讨论】:

    标签: android dialog


    【解决方案1】:

    您正在寻找创建对话框而不是对话框本身的 Activity 中的按钮。 findViewById 行应该是:

    Button ok = (Button)searchDialog.findViewById(R.id.OkButton);
    

    【讨论】:

    • kichik,你的明星!!这让我困扰了一段时间。
    • 非常感谢!您节省了我排除故障的时间!
    猜你喜欢
    • 2015-10-29
    • 2012-03-09
    • 2019-07-18
    • 2015-03-27
    • 1970-01-01
    • 2011-06-03
    • 2014-09-06
    • 2014-07-19
    • 2017-01-05
    相关资源
    最近更新 更多