How to use Dialog OnClick Listner in Android?
I am new to Android development. Please excuse me If my question is very simple.
I have tried to create a button on my Android Layout view using XML. Now within the Activity class I am trying to get the button and add a on click listner to it. This is working fine without any issues.
On similar lines on the button click i explained previously I have a dialog being popped up. In this dialog I have a ImageButton. On click of this Image button I am trying to set a on click listner using the below code.
The Activity on create is as below
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = (Button) findViewById(R.id.btnAdd);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final Button btnAdd = (Button) findViewById(R.id.btnAdd);
if(v==btnAdd) {
dialog = new Dialog(this);
dialog.setContentView(R.layout.add_dialog);
dialog.setTitle("Test Title.");
dialog.setCancelable(true);
dialog.show();
final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
try {
Log.i("Log","1");
button.setOnClickListener(this);
Log.i("Log","2");
}
catch(Exception e)
{
Log.i("Log","3");
dialog.dismiss();
//Dialog d = new Dialog(this);
//d.setTitle("test.");
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
Toast.makeText(this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
Log.i("Log","4");
//d.show();
Log.i("Log","5");
}
}
}
In the above I get the Log in this sequence. 1,3,4,5. I dont get the 2. In the toast i get message of blank, blank followed by java.lang.Nullexception.
But this when executed gives me a force close pop up. Please advice how to do this. Or is there any workaround for the same? I need to have a dialog box to come on a button click, and then within the dialog I need to have more than one option of buttons. For each of buttons in the dialog I need to perform different activities. Any kind 开发者_运维问答of help or advice is appreciable. Thank you in advance for your time and help.
Most probably you are trying to retrieve the button from the Activity
class. It returns null because this method will only retrieve resources attached to the Activity (by using the method setContentView
).
You have two options:
- You can inflate the dialog layout using a LayoutInflater
- If you are extending the Dialog class, add the listener inside that class instead.
Edit after the update:
As I said above, the problem is:
final ImageButton button = (ImageButton) findViewById(R.id.imageButton1);
because imageButton1 is not part of the layout in the activity. Just replace it by:
final ImageButton button = (ImageButton) dialog.findViewById(R.id.imageButton1);
精彩评论