android - Showing a DialogFragment object from an on click inside a button listener -
i trying showing dialogfragment object on click inside button listener.
here code of activity should start dialog:
import android.os.bundle; import android.app.activity; import android.content.context; import android.content.intent; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; public class mainactivity extends activity { button button1; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); addlistenertobutton1(); } private void addlistenertobutton1(){ final context context = this; button1 = (button) findviewbyid(r.id.button1); button1.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { dp ciao = new dp(); ciao.show(this,"mydp"); } }); } }
and here's code of dialog:
public class dp extends dialogfragment { @override public dialog oncreatedialog(bundle savedinstancestate) { // use builder class convenient dialog construction alertdialog.builder builder = new alertdialog.builder(getactivity()); builder.setmessage("prova") .setpositivebutton("pos", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int id) { } }) .setnegativebutton("neg", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int id) { } }); return builder.create(); } }
errors are:
the method show(fragmentmanager, string) in type dialogfragment not applicable arguments (mainactivity, string)
the method show(fragmentmanager, string) in type dialogfragment not applicable arguments (new view.onclicklistener(){}, string)
any advice?
try method of passing correct context dialogfragment
button1.setonclicklistener(new onclicklistener() { @override public void onclick(view view) { dp ciao = new dp(); ciao.show(view.getcontext(),"mydp"); } });
in original code, when calling
'ciao.show(this,"mydp");'
the refers parent class onclicklistener.
when assigning click listener , overriding onclick, passed view , argument can use access information from, including context.
Comments
Post a Comment