JK.C
JK.C

Reputation: 97

How to call Fragment from OnClickListener

I am working in Fragment. i want to call one fragment from onClickListener. how can i do that? This is my code. from the else part i have to call one fragment..how to do that?

  chartView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SeriesSelection seriesSelection = chartView
                        .getCurrentSeriesAndPoint();

                if (seriesSelection == null) {
                    Toast.makeText(getActivity().getApplicationContext(),
                            "No chart element was clicked",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(
                            getActivity().getApplicationContext(),
                            "Chart element data point index "
                                    + (seriesSelection.getPointIndex() + 1)
                                    + " was clicked" + " point value="
                                    + seriesSelection.getValue(),
                            Toast.LENGTH_SHORT).show();


                }
            }
        });

Upvotes: 1

Views: 1638

Answers (2)

katzoft
katzoft

Reputation: 868

I think what you want is to call a method in another Fragment that is already added. This is done via the Activity that both Fragments share. There's a guide here: http://developer.android.com/training/basics/fragments/communicating.html

Upvotes: 0

Imtiyaz Khalani
Imtiyaz Khalani

Reputation: 2053

There are many ways to replacing Fragments. but I follow the way below:

Create addFragmentMethod() like below

 public void addFragments(Fragment fragment) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(android.R.id.tabcontent, fragment);
    ft.commit();
}

now override onAttach() like this

@Override
public void onAttach(Activity activity) {
    this.activity = (YourActivity) activity;
    myDetail = this.activity.myDetail;
    super.onAttach(activity);
    }

now just call

activity.addFragments(fragment);

Upvotes: 3

Related Questions