Android中onCreateDialog中的错误

时间:2011-04-28 06:28:34

标签: android dialog nullpointerexception

我在此代码中的onCreateDialog()NullPointerException中有错误:

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class More extends Activity{
    static int DIALOG_ID=0;
     Dialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myfavourate);
        //showDialog(DIALOG_ID);

    }
    protected Dialog onCreateDialog(int id) {

        switch(id) {
        case 0:
            // do the work to define the pause Dialog

            dialog = new Dialog(this);
            dialog.setContentView(R.layout.more);
            dialog.setTitle("Please Select One:");
            Button btn_setting = (Button)findViewById(R.id.btn_more_setting);
            Button btn_about = (Button)findViewById(R.id.btn_more_about);
            Button btn_privacy = (Button)findViewById(R.id.btn_more_privacy);
            Button btn_cancel = (Button)findViewById(R.id.btn_more_cancel);
            btn_setting.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(More.this,SettingActivity.class);
                    startActivity(intent);
                }
            });

            btn_about.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(More.this,About.class);
                    startActivity(intent);

                }
            });

            btn_privacy.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(More.this,Privacy_Policy.class);
                    startActivity(intent);

                }
            });

            btn_cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    More obj = new More();
                    obj.finish();
                }
            });
            break;

        default:
            dialog = null;
        }
        return dialog;
    }

}

1 个答案:

答案 0 :(得分:0)

修复

Button btn_setting = (Button)findViewById(R.id.btn_more_setting);

Button btn_setting = (Button) dialog.findViewById(R.id.btn_more_setting);

为其他按钮执行此操作。

诀窍是当你只是调用findViewById时,会调用它来进行活动,并且没有对话按钮膨胀。相反,它们会膨胀到对话框中,您应该在对话框中搜索它们。