Calling A Method From A Fragment Inside A Mainactivity
Solution 1:
The issue seems to be that you are calling displayFragment1();
in your Activity's onCreate
and yet you are expecting to find Fragment_2
which you are only setting/initializing in displayFragment2();
- you never call this method.
So, please change your code in the onCreate
method to call displayFragment2()
like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayFragment2();
}
UPDATE:
Please add the call getSupportFragmentManager().executePendingTransactions()
after the commit statement and then try looking up the Fragment
by TAG and see if this at least returns a Fragment
object and not null. Your code will now look like:
...
FragmentTransactionfragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, newFragment_2(), "frag2");
fragmentTransaction.commit();
getSupportFragmentManager().executePendingTransactions()
Fragment_2fragment= (Fragment_2) getSupportFragmentManager().findFragmentByTag("frag2");
fragment.setChangeTo(text);
I hope this helps.
Solution 2:
You should declare a FrameLayout in your Activity's layout xml where the fragments you want will be inflated. Then use that FrameLayout's id when making a transaction instead of android.R.id.content.
Solution 3:
The way to handle this is:
Fragmentfragment= getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof YourFragmentClass) {
fragment.setChangeTo(value);
}
Post a Comment for "Calling A Method From A Fragment Inside A Mainactivity"