问题描述
我正在尝试使用自定义对话框创建模态视图,这是 myDialog.java 类:
public class MyDialog extends Dialog implements android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button btnaddsingleingredient,btncanceladdingsingleingredient;
public MyDialog(Activity a) {
super(a);
// Todo Auto-generated constructor stub
this.c = a;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestwindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.my_dialog);
btnaddsingleingredient = (Button) findViewById(R.id.btnaddsingleingredient);
btncanceladdingsingleingredient = (Button) findViewById(R.id.btncanceladdingsingleingredient);
btnaddsingleingredient.setonClickListener(this);
btncanceladdingsingleingredient.setonClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnaddsingleingredient:
d.dismiss();
break;
case R.id.btncanceladdingsingleingredient:
d.dismiss();
break;
default:
break;
}
dismiss();
}
}
这是我调用对话框的类:
public class AggiungiIngredientiActivity extends AppCompatActivity {
ImageButton btnAddNewIngredient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aggiungi_ingredienti);
btnAddNewIngredient = findViewById(R.id.btnAddNewIngredient);
btnAddNewIngredient.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
MyDialog addIngredientDialog = new MyDialog(AggiungiIngredientiActivity.this);
addIngredientDialog.btncanceladdingsingleingredient = findViewById(R.id.btncanceladdingsingleingredient);
addIngredientDialog.btnaddsingleingredient.findViewById(R.id.btnaddsingleingredient).setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
基本上我想打开一个模态视图让用户插入一些数据,但它给了我错误:
Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
它说问题出在这里:
addIngredientDialog.btnaddsingleingredient.findViewById(R.id.btnaddsingleingredient).setonClickListener(new View.OnClickListener())) { ... }
我不知道这是否是进行模态视图的最佳方式(我愿意接受建议),如果您需要 xml,我可以更新帖子,但我认为它不相关
更新 1: 我也试过
btnaddsingleingredient = (Button) findViewById(R.id.btnaddsingleingredient); //Replace sat1 with id defined in XML layout
代替
addIngredientDialog.btnaddsingleingredient.findViewById(R.id.btnaddsingleingredient).setonClickListener
解决方法
解决了这个问题,我把解决方案放在这里,以防有人也需要它。
基本上不是创建一个扩展 Dialog 的自定义类,而是使用类 Dialog 然后使用 dialog.setContentView(R.layout.yourlayout);
然后你用 dialog.findViewById(R.id.idbuttoninthecustomalert);
引用按钮
最后你可以在没有空引用的情况下设置OnClickListener!
Dialog mydialog;
Button button,mydialog = new Dialog(context.this);
mydialog.setContentView(R.layout.yourlayout);
button= mydialog.findViewById(R.id.buttonid);