This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez on-line!
See this thread for details.
The moose likes Android and the fly likes Passing a class type to a constructor and use it in a cast statement. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Mobile » Android
Bookmark "Passing a class type to a constructor and use it in a cast statement." Watch "Passing a class type to a constructor and use it in a cast statement." New topic
Author

Passing a class type to a constructor and use it in a cast statement.

William Fears
Greenhorn

Joined: Jul 18, 2013
Posts: 2
I'm trying to understand the best way to organize the two classes below. The sample code, I'm working with, had the DetailFragment as a nested class within ListViewTest. I would like to move DetailFragment into it's own class allowing me to init from any object. The only problem I see is the cast on line 19: ((ListViewTest) getActivity()).doPositiveClick();

What if I wanted to use DetailFragment with a class called ListViewNew? How would I know which class to cast to?



Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Welcome to the Ranch.
I will move your topic over to the Android forum, where Android related questions are discussed


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

You do it the same way you would if you had multiple implementations in normal classes. You create an interface which contains the method(s) you want to call from the activity. Then you have the activities implement the interface. In the Fragment you cast to the interface, not the activity implementation.


Steve
William Fears
Greenhorn

Joined: Jul 18, 2013
Posts: 2
Thank you, this explanation really helped me understand interfaces too!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Passing a class type to a constructor and use it in a cast statement.