0

Button が初期化されているのに NullPointerException が発生する理由がわかりません。これが私のコードです。皆さんが助けてくれることを願っています。ありがとう

public boolean onOptionsItemSelected(MenuItem item)
{   switch (item.getItemId())
        {   
            case SEARCH:
                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                AlertDialog.Builder search = new AlertDialog.Builder(this);
                search.setTitle(R.string.search);
                searchDialog = inflater.inflate(R.layout.search,null);
                search.setView(searchDialog);

                   //The problem should be here
                searchButton = (Button) findViewById(R.id.searchButton);
                   //R.id.searchButton is inside the layout, search.xml
                searchButton.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {   //For testing
                        Toast.makeText(getApplicationContext(), 
                                "Search was clicked!", Toast.LENGTH_SHORT).show();
                    }
                });
                AlertDialog searchDialog = search.create();
                searchDialog.show();
                return true;
                .
                .
                .
4

1 に答える 1

1
searchDialog = inflater.inflate(R.layout.search,null);

上記の行が変更され、ボタンを初期化するにはビューの参照を使用する必要があります。

public boolean onOptionsItemSelected(MenuItem item)
{   switch (item.getItemId())
        {   
            case SEARCH:
                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                AlertDialog.Builder search = new AlertDialog.Builder(YourActivity.this);
                search.setTitle(R.string.search);
                View view = inflater.inflate(R.layout.search,null);
                search.setView(view);

                   //The problem should be here
                searchButton = (Button)view.findViewById(R.id.searchButton);
                   //R.id.searchButton is inside the layout, search.xml
                searchButton.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {   //For testing
                        Toast.makeText(getApplicationContext(), 
                                "Search was clicked!", Toast.LENGTH_SHORT).show();
                    }
                });
                AlertDialog searchDialog = search.create();
                searchDialog.show();
                return true;
                .
                .
                .
于 2012-06-02T16:20:05.140 に答える