I checked all the similar tickets with "getSupportFragmentManager().findFragmentById returns null" but none helped.
In Android Studio 3.0.1 I just created a new project based on the "Tabbed Activity" template project and navigation style set to "Action Bar Tabs (with ViewPager)".
Then I added 3 xml files
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment1">
<!-- @+id/fragment2 in fragment2.xml-->
<!-- @+id/fragment3 in fragment3.xml-->
...some controls
</LinearLayout>
And the 3 corresponding .java class files
public class Fragment1 extends Fragment {
//Fragment2, Fragment3
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
//R.layout.fragment2, R.layout.fragment3
}
}
In the SectionsPagerAdapter class of MainActivity class, I changed the overriden method getItem to the following.
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch(position) {
case 0: return new Fragment1();
case 1: return new Fragment2();
case 2: return new Fragment3();
default:
return new Fragment1();
}
//return PlaceholderFragment.newInstance(position + 1);
}
And finally, I want to trigger something in my first fragment.
public void onClick(View view) {
Fragment1 frag1 = (Fragment1) getSupportFragmentManager().findFragmentById(R.id.fragment1);
}
My problem is that when I click a button in the toolbar and I reach its onClick event (in MainActivity), my frag1 is always null!
Please help! :)