Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've seen in many Java code notation that after a method we call another, here is an example.

Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();

As you see after calling makeText on the return we call setGravity and so far

How can I do this with my own classes? Do I have to do anything special?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

This pattern is called "Fluent Interfaces" (see Wikipedia)

Just return this; from the methods instead of returning nothing.

So for example

public void makeText(String text) {
    this.text = text;
}

would become

public Toast makeText(String text) {
    this.text = text;
    return this;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...