This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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 Murach's Java Servlets and JSP this week in the Servlets 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: 10167
    
    8

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: 4165
    
  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!
 
 
subject: Passing a class type to a constructor and use it in a cast statement.
 
Similar Threads
ArrayList object not passing to String[]
How to get values ?
activity doesn't wait untill alertdialog completes
How to handle input from a Dialog ?
How to check equality of strings ?