简体   繁体   中英

How do I pass data from a class to a fragment?

I'm trying to create some fragments for an app and wanted to use one class to represent its data like names, levels, health, etc.

So inside my fragment I'm currently working on, I only know how to use the data declared in its own class file and applying it to a spinner. Below is the code for it and works perfectly how I want it to. But I want to have a class file with just data variables so I can use globally between all my fragments and not repeat the code over and over again. Below is my code inside of my fragment that I have now.

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_hunt, container, false);

        String [] names = {"Peter Pan", "Captain Hook", "Jack Sparrow"};

        Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, names);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner.setAdapter(adapter);

        return view;
    }

So really, does anyone know how would I pull the data from the below pure java class into this fragment so I can use them between many fragments?

The class I have below is the one I created just to store my data variables.

public class TreasureHunter {

    public static String[] name = new String[] {
            "Peter Pan",
            "Captain Hook",
            "Jack Sparrow"
    };

    public static int[] picturePath = new int[] {
            R.drawable.peter,
            R.drawable.hook,
            R.drawable.jack
    };

    public static int[] health = new int[] {
            120,
            100,
            110

    };
}

Not sure if I understand you correctly but if you want to pull/save data from a static class you just call it as is : String[] names = TreasureHunter.name . The fragment has nothing to do with it.
Edit
Additionally from a more OOP approach you could create a class "Character" with name, image, health, etc variables. Create a class with a static array of characters "roster". Then build your characters: Character peterPan = new Character(name, img, health) then add to your roster array. That way you have an array of individual characters instead of arrays you need to keep in parrallel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM