1

I have an Activity. When I click on the button, I want to run the method in Fragment. But it does not work. I tried many ways, but I could not get it working.

My Activity;

public class MyActivity extends Activity {

Button button;
TabLayout tabLayout;

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

    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("First"));
    tabLayout.addTab(tabLayout.newTab().setText("Second"));

    viewPager= (CustomViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
    });        

    button = (Button)findViewById(R.id.button);
    button .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            MyFragment firstfragment = (MyFragment ) getFragmentManager().findFragmentByTag(“tab1”); 

            firstfragment.MyMethod();
        }
    });
    }
}

MyFragmentAdapter

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.webviewapp.Fragment.PromotionFragment;
import com.webviewapp.Fragment.WebFragment;

public class MyFragmentAdapter extends FragmentPagerAdapter {

int tabCount;

public MyFragmentAdapter(FragmentManager fm, int numberOfTabs) {
    super(fm);
    this.tabCount = numberOfTabs;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            FirstFragment tab1 = new FirstFragment ();
            return tab1;
        case 1:
            SecondFragment tab2 = new SecondFragment ();
            return tab2;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return tabCount;
}
}

FirstFragment

 public class FirstFragmentextends Fragment {

 Button fragmentbutton;

 public FirstFragment() {
    // Required empty public constructor
}


@SuppressLint("SetJavaScriptEnabled")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_web, container, false);

    fragmentbutton = (Button) view.findByViewId(R.id.fragmentbutton );
}

 public void MyMethod(){

   fragmentbutton.setVisibility(View.GONE);
}

}

I'm sorry to cause confusion. What I'm trying to do is to run MyMethod when I press the button in Activity. MyMethod is a special method in the fragment. I apologize again for not being able to add the codes at first.

  • Are you sure that you want to create a new instance of your fragments in the onclick? What is the method supposed to do? You need to somehow show the fragment if you want to see its content – StarterPack Aug 21 '18 at 19:17
  • @Isa, You cant call a method just by it's object without the fragment being loaded. Have you loaded the fragment in the activity.. If yes, show the code please. – Ümañg ßürmån Aug 21 '18 at 19:18
  • @StarterPack I do not really want to create a new fragment. I want to access the fragmenti when I click the button. The object inside the fragment is enough. I could not run anything. –  Aug 21 '18 at 19:39
  • @UmangBurman I tried to add the relevant parts of my code to the picture. Please check. –  Aug 21 '18 at 19:39
  • 1
    "does not work" is not a useful problem description. Please be specific. – glennsl Aug 21 '18 at 19:45
  • Why not have the button in the fragment if the fragment is already running? Unless you want to open a new fragment with that button? – Mr.O Aug 21 '18 at 19:50
  • If we have to say based on the screenshots, the code is pretty incorrect (you are creating instance on each click). Put a console log in method you want to invoke. It will be called but just on fragment instance which is not shown. – Borislav Kamenov Aug 21 '18 at 19:51
  • @Mr.O Fragment is running. I use TabLayout. Please look at the screen image. –  Aug 21 '18 at 20:16
  • @BorislavKamenov I used it. I could not work again. I used it. I could not work again. –  Aug 21 '18 at 20:18
  • try this https://stackoverflow.com/a/73796270/13560080 – Zahid Iqbal Sep 21 '22 at 06:35

3 Answers3

4

If you want to call a method from FirstFragment

FirstFragment firstFragment = (FirstFragment) getSupportFragmentManager().getFragments().get(0);
firstFragment.MyMethod();

If you want to call a method from SecondFragment

SecondFragment secondFragment = (SecondFragment) getSupportFragmentManager().getFragments().get(1);
secondFragment.MyMethod();

The index 0 or 1 based on position in getItem method of your adapter.

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            FirstFragment tab1 = new FirstFragment();
            return tab1;
        case 1:
            SecondFragment tab2 = new SecondFragment();
            return tab2;
        default:
            return null;
    }
}

Then give it a try.

Son Truong
  • 13,661
  • 5
  • 32
  • 58
1

You use FragmentManager to get a handle on the fragment. You are making a new instance of a Fragment in your code:

final FirstFragment firstfragment= new FirstFragment ();

Where that new object is not bound to any activity.

FragmentManager

Jcov
  • 2,122
  • 2
  • 21
  • 32
  • I used this, but doesn't work. WebFragment = (WebFragment ) getFragmentManager().findFragmentByTag(“tab1”); –  Aug 21 '18 at 19:43
  • Your lack of code isn't helping people. Show the full activity and fragment classes. – Jcov Aug 21 '18 at 20:10
  • Please check. I can finally add. –  Aug 21 '18 at 20:37
0

Too late for answering the question but this is a easy way to get fragment instance and call methods in a fragment; you have to get instance of your fragment then call your public method:

In your fragment :

 private static yourFragment instance;

then in onCreateView of your fragment :

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

        instance= this;

        View v = inflater.inflate(R.layout.fragment_tools, container, false);
        binding = FragmentToolsBinding.inflate(inflater, container, false);

        return v;
    }

and also in your fragment you have to have a static method that returns the instance:

public static yourFragment GetInstance()
{
    return instance;
}

then you have a public method in in your fragment that you want to call it like this:

public  void  theMethod()
{
    Toast.makeText(getActivity(), "Test", Toast.LENGTH_SHORT).show();
}

then you can get fragment instance and call your non static public method like this:

yourFragment frag = yourFragment.GetInstance(); frag.theMethod();

da jowkar
  • 181
  • 1
  • 8