error in onCreateDialog in Android
I have an error in onCreateDialog() NullPointerException in this code:
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_mo开发者_开发知识库re_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;
}
}
Fix
Button btn_setting = (Button)findViewById(R.id.btn_more_setting);
to
Button btn_setting = (Button) dialog.findViewById(R.id.btn_more_setting);
And do this for other buttons.
The trick is that when you simply call findViewById, it is called for the activity, and it doesn't have you dialog buttons inflated. Instead they are inflated to the dialog, and you should search them within dialog.
精彩评论