Reputation: 583
i have a code like this, this just an example class with an object of a class with an event listener.
public class MyActivity ..... {
EditText something;
AnyFragment frag;
public MyActivity(){
frag = new AnyFragment();
}
public void setText(String text){
something.setText(text);
}
}
public class AnyFragment extends DialogFragment implements AnyListener{
public void onEvent(String text){
// How to call method setText in class MyActivity from here ?
}
}
My problem is: how to call method setText in class MyActivity while event on frag object is triggered?
or there's another approach to do that?
Any answer would be appreciated, thanks!
Upvotes: 2
Views: 496
Reputation: 17142
You can do this:
public class MyActivity ..... {
EditText something;
AnyFragment frag;
public MyActivity(){
frag = new AnyFragment(this);
}
public void setText(String text){
something.setText(text);
}
}
public class AnyFragment extends DialogFragment implements AnyListener{
private Context context;
public AnyFragment(Context context) {
this.context = context;
}
public void onEvent(String text){
((MyActivity)context).setText(text);
}
}
or using an interface
:
public class MyActivity ..... {
EditText something;
AnyFragment frag;
public MyActivity(){
frag = new AnyFragment();
frag.setFragListener(new AnyFragment.FragListener() {
@Override
public void notifyActivity(String text) {
setText(text);
}
});
}
public void setText(String text){
something.setText(text);
}
}
public class AnyFragment extends DialogFragment implements AnyListener{
private FragListener listener;
public setFragListener(FragListener listener) {
this.listener = listener;
}
public void onEvent(String text){
if(listener != null)
listener.notifyActivity(text);
}
public interface FragListener {
void notifyActivity(String text);
}
}
Upvotes: 2