protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ds = new DataSource(getApplicationContext());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myDialog = new Dialog(view.getContext());
myDialog.setContentView(R.layout.popup_add_customers);
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "savebutton", Toast.LENGTH_LONG).show();
}
});
myDialog.show();
}
});
}
现在我只想在“保存”按钮上举杯。
它给我下面的错误
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
提前感谢,真的需要帮助...
答案 0 :(得分:0)
您的问题出在btnSave findViewById
像这样改变
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myDialog = new Dialog(view.getContext());
myDialog.setContentView(R.layout.popup_add_customers);
btnSave = (Button)myDialog.findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "savebutton", Toast.LENGTH_LONG).show();
}
});
myDialog.show();
}
});
答案 1 :(得分:0)
您正在尝试将findViewById
插入对话框中的btnSave
。您需要在对话框上调用findViewById
:
btnSave = (Button)myDialog.findViewById(R.id.btnSave);
答案 2 :(得分:0)
请勿放置
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "savebutton", Toast.LENGTH_LONG).show();
}
});
在OnClick方法中,您需要将其放在OnCreate方法中
尝试一下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ds = new DataSource(getApplicationContext());
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "savebutton", Toast.LENGTH_LONG).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myDialog = new Dialog(view.getContext());
myDialog.setContentView(R.layout.popup_add_customers);
myDialog.show();
}
});
}