简体   繁体   中英

How can pass data from Adapter to Fragment?

How can pass data between adapter and fragment ?

My adapter:

finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        finalHolder.spinner.setSelection(position);
        selState = finalHolder.spinner.getSelectedItem().toString();
        System.out.println(selState);
        Toast.makeText(getContext(),
                "Clicked on Planet: " + selState + "", Toast.LENGTH_SHORT).show();

        Fragment fragment = new Fragment();
        Bundle bundle = new Bundle();
        bundle.putString("key", selState);
        Log.i("BUNDLE", bundle.toString());
        fragment.setArguments(bundle);
    }
});

My fragment:

public  class MyListFragment extends Fragment{

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        /*Bundle bundle = this.getArguments();
        String strtext = bundle.getString("key", " ");
        System.out.println(strtext);*/
        System.out.println("prima ancora");

        Bundle arguments = this.getArguments();
        System.out.println("prima");
        if (arguments != null) {
            System.out.println("dopo");

            //String userId = arguments.getString("key");
                //System.out.println("finalmente:"+userId);
             user = getArguments().getString("Key");


        } 

}

You can use Interface to pass data from the adapter to the fragment, and generally, you can find it here: Java - Interface

In your case you can implement an interface like this:

Public Interface YourInterfaceName{
    void onItemSelected(String key, String Value);
}

in your fragment you have to implement your intrface:

public class YourFragment extends Fragment implements YourInterface
{
    YourAdapter.setOnItemSelected(this);
}

and finlay in your adapter do this:

public class Adapter
{
    public void setOnItemSelected(YourInterface yourIntrface)
    {
         this.yourIntrface = yourIntrface;
    }
    .......
    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
.....
     //instead of creating instance of fragment do this:
     yourInterface.onItemSelected(yourKey, value);     
}

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