我想在启动应用程序时显示自定义对话框,并且没有任何事件要触发,例如按钮单击。我将自定义对话框放在onCreate()
中,但应用程序在NullPointerException
处为btnDecline.setOnClickListener
处理了。
MainActivity.java
public class MainActivity extends Activity {
private Button btnRegister, btnDecline, btnAccept;
private EditText etRegisterName, etRegisterEmail;
private Dialog terms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
btnRegister = (Button)findViewById(R.id.btnRegister);
etRegisterName = (EditText)findViewById(R.id.etRegisterName);
etRegisterEmail = (EditText)findViewById(R.id.etRegisterEmail);
btnRegister.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String name = etRegisterName.getText().toString();
String email = etRegisterEmail.getText().toString();
}
});
showTermsConditions();
}
private void showTermsConditions(){
terms = new Dialog(MainActivity.this);
terms.setContentView(R.layout.terms_conditions_dialog);
btnDecline = (Button) findViewById(R.id.btnDecline);
btnAccept = (Button) findViewById(R.id.btnAccept);
terms.setTitle("Terms and Conditions");
terms.show();
btnDecline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
moveTaskToBack(true);
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
terms.dismiss();
}
});
}
}
答案 0 :(得分:2)
更改为
terms.setContentView(R.layout.terms_conditions_dialog);
btnDecline = (Button) terms.findViewById(R.id.btnDecline);
btnAccept = (Button) terms.findViewById(R.id.btnAccept);
按钮属于Dialog
。您需要在该视图层次结构中查找视图。
findViewById
在当前视图层次结构中查找视图。按钮btnDecline
和btnAccept
不属于register.xml
。它们属于terms_conditions_dialog.xml
,它是Dialog的布局。
答案 1 :(得分:0)
你正在错误的地方看按钮ID
private void showTermsConditions(){
terms = new Dialog(MainActivity.this);
terms.setContentView(R.layout.terms_conditions_dialog);
btnDecline = (Button) terms.findViewById(R.id.btnDecline);
btnAccept = (Button) terms.findViewById(R.id.btnAccept);
terms.setTitle("Terms and Conditions");
terms.show();
btnDecline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
moveTaskToBack(true);
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
terms.dismiss();
}
});
}