3
My doubt is knowing the best way to work for the organization of methods, I will present 2 implementation options that I am in doubt, whenever I have in Fragment a reference through getActivity() I should use interface?:
1st option : I’m stating directly in Fragment the getActivity():
Toast.makeText(getActivity(), "mensagem", Toast.LENGTH_LONG).show();
2nd option : I created a interface with the method:
public void mensagemToast();
Then in the Activity I have implemented this method using the this(Activity):
@Override
public void mensagemToast() {
Toast.makeText(this, "mensagem", Toast.LENGTH_LONG).show();
}
Then I created a Listener no Fragment to call this method that is implemented in the Activity:
listener.mensagemToast();
This is just one example I have several cases similar to this that in Fragment I call directly the getActivity(). What is the best form among the options I presented?
1st that seems to be more simple but, is picking up a direct reference from Activity?
2nd that is more bureaucratic but decoupled (separate) from Fragment?
Or is there another solution that is better than the above?
um... very good your answer... but I’m still doubtful only on the part of choosing between using without/with interface in the example I gave.. or in my question I must choose the first option or the second?
– Pedro Rangel
2nd option - Use a interface
– ramaral
blz vlw +1 in his reply
– Pedro Rangel
just disturbing one more time.. in case I create a Alertdialog.Builder Builder = new Alertdialog.Builder(getActivity()); in Fragment it would also be necessary to create an interface, that is, whenever in Fragment use getActivity() I should always use an interface?
– Pedro Rangel
I don’t know what you mean by that example. But when you ask if "always must", my answer is: depends on the context. Standards and good practice should not be followed just because someone says so. Context must be taken into account: the benefit must be greater than the cost.
– ramaral