Lion789
Lion789

Reputation: 4482

How to implement listener interface in fragment?

I am trying to communicate between an activity and the fragment that sits on top of it, I want new data (image/text - retrieved from the db) to be passed into the frag every time an onclick occurs (onclick is in the activity). I made a simple interface to test (let me know if this is not suitable for images or if it is too slow or inefficient), and I am trying to have it included in my fragment so when an onclick occurs the fragment changes the image and the text.

Here is the simple interface code:

public interface FragmentCommunicator {
    public void passDataToFragment(String someValue);
}

Here is the activity code:

public class RandomActivity extends FragmentActivity implements ActivityCommunicator {

    //viewpager adapter
    private PageAdapter mAdapter;
    private ViewPager viewPager;

    //interface through which communication is made to fragment
    public FragmentCommunicator fragmentCommunicator;

    //Buttons for yes, no, skip
    Button btnYesRandom, btnNoRandom, btnSkipRandom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random);

        //set buttons
        btnYesRandom = (Button) findViewById(R.id.btnYesRandom);

        // Initializing pager
        viewPager = (ViewPager) findViewById(R.id.random_pager);

        //calling bundle to attach data to fragment
        Bundle bundle = new Bundle();
        bundle.putString("edttext", "From Activity");

        // set Fragmentclass Arguments
        RandomFragment randFrag = new  RandomFragment();
        randFrag.setArguments(bundle);

        //Setting up fragment
        FragmentManager fm = getFragmentManager();
        mAdapter = new PageAdapter(getSupportFragmentManager(),  new UserUpVotesFragment(), randFrag, new UserDownVotesFragment());
        viewPager.setAdapter(mAdapter);
        // Here you would declare which page to visit on creation
        viewPager.setCurrentItem(1);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {}
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            public void onPageSelected(int position) {
                // Check if this is the page you want.
                if(position !=1) {
                    //swiping to the right
                    if(position == 0) {
                        Log.e("Swiping", "SWIPING TO THE Right BUT RESET ERR");
                        getIntent().removeExtra("edttext");
                    }

                    //swiping to the left
                    if(position == 2) {
                        Log.e("Swiping", "SWIPING TO THE left BUT RESET ERR");
                    }

                    // RandomFragment randomFrag = (RandomFragment) getFragmentManager().findFragmentById(R.id.fra);

                    viewPager.setCurrentItem(1);
                }
            }
        });

        btnYesRandom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                if(fragmentCommunicator != null)
                    fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
            }
        });
    }

Code for Fragment:

public class RandomFragment extends Fragment {

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

        //call data from activity bundle
        String strtext = getArguments().getString("edttext");

        View rootView = inflater.inflate(R.layout.fragment_random, container, false);

        RelativeLayout random_frag_layout = (RelativeLayout) rootView.findViewById(R.id.random_frag_layout);

        activityButton = (ImageView) rootView.findViewById(R.id.imagehere);
        //setRetainInstance(true);

        texthere = (TextView) rootView.findViewById(R.id.texthere);
        texthere.setText(strtext);

        return rootView;
    }

    //FragmentCommunicator interface implementation
    public void passDataToFragment(String someValue){
        activityAssignedValue = someValue;
        Log.e("ACTIVITY", activityAssignedValue);
    }
}

Upvotes: 1

Views: 7729

Answers (2)

Dmide
Dmide

Reputation: 6462

If you have only one fragment, then you can access it directly and send any data just via method: make your fragment a field and call your passDataToFragment() on it from activity.

To access an activity from fragment, call ((RandomActivity)getActivity()).activityMethod()

Upvotes: 4

Ken
Ken

Reputation: 31161

What is ActivityCommunicator?

If you wish to go down this route have your RandomActivity class implement the FragmentCommunicator interface, which should either be declared as an inner-public interface in the RandomFragment class say, or publicly (or package local) in its own file.

Upvotes: 0

Related Questions