How do I add structure to UI built on Fragments? - java

I build an app, which consists of Activity and Fragments, which reside in the Activity.
I replace Fragments according with the app flow, but it seems that as more actions are added to the app, it becomes more hard to keep track of the app flow in code.
Suppose this:
public class MainActivity extends Activity{
private enum AppState {
WAIT_SIGN_IN, SCAN_PERSONAL_ID, CONFIRM_ORDER, PICK_ITEM, NAVIGATE_TO_ITEM
}
private AppState currentState = AppState.WAIT_SIGN_IN;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setWaitSignInContent();
}
//Hardware key is pressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (currentState) {
case WAIT_SIGN_IN:
setSignInContent();
currentState = AppState.SCAN_PERSONAL_ID;
break;
case PICK_ITEM:
handlePickItem();
default:
break;
}
return true;
}
//Callback from barcode scanner
#Override
public void onCodeScanned(String code) {
switch (currentState) {
case SCAN_PERSONAL_ID:
if (checkPersonalId(code)) {
setSignInSuccessContent();
}
break;
default:
break;
}
}
private void setSignInSuccessContent() {
Fragment fragment = new ImageFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_primary, fragment).commit();
}
private void setSignInContent() {
Fragment fragment = new ScannerFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_primary, fragment).commit();
}
private void setWaitSignInContent() {
Fragment fragment = new ImageFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_primary, fragment).commit();
}
}
}
As you can see, this state-based flow is hard to follow. Any suggestions on how to improve that?

i'm follow this way to replace fragment
create method in your activity for adding and replacing.
public void addFragments(Fragment fragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
// ft.setCustomAnimations(R.anim.fragment_from_right,
// R.anim.fragment_from_left, R.anim.fragment_from_right,
// R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
// remove all fragments from the stack
public void removeAllFragment(Fragment replaceFragment, boolean animate,
boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
manager.popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
if (animate) {
// ft.setCustomAnimations(R.anim.slide_in_right,
// R.anim.slide_out_left);
// ft.setCustomAnimations(R.anim.fragment_from_right,
// R.anim.fragment_from_left, R.anim.fragment_from_right,
// R.anim.fragment_from_left);
}
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, replaceFragment);
ft.commit();
}
now override in Fragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof MainActivity) {
mainActivity = (MainActivity) activity;
}
}
now just call in fragment for replace like
mainActivity.addFragments(new BusinessDetail(), true, tr, null);
enjoy i hope it helps.

Since there seems to be only one activity in your app, you migh consider using the singleton pattern (the activity itself being that singleton, obviously). For example, your interface may look like this:
public void addFragment(Fragment fragment, boolean replaceTopFragmentInStack);
public void removeFragment(Fragment fragment);
public void removeFragment(int index);
public void removeTopFragment();
public void clearFragmentStack();
Not only you will be able to easily control the flow, but you will also have access to these methods from anywhere in the app via something like MainActivity.getInstance().removeTopFragment()

Related

Android - NullPointerException in Fragment after callback

This is the first time I work with Fragments and I don't understand very well how to manage them. In this case I have two fragments that I show dinamically in a FrameLayout with id fragment_place. The issue is probably with the fragmentTransaction(addtobackstack / popbackstack).
In Fragment2 I show a popupmenu when I press the menubutton on the mobile and it works as expected the first time, but after I go back to the previous fragment and return to fragment2 now If I press the menubutton I get the following error
java.lang.NullPointerException
at android.support.v7.view.menu.MenuBuilder.<init>(MenuBuilder.java:216)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:103)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:78)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:63)
at package.Fragment2.showPopup(Fragment2.java:93)
Below is the code for the mainactivity and fragment2, this is driving me crazy, any help will be much appreciated.
public class MainActivity extends AppCompatActivity implements Fragment1.onEvent {
Fragment1 frag;
Fragment2 frag2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag = new Frag1();
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place, frag);
ft.commit();
}
#Override
public void onEventSelected(String key) {
frag2 = new Frag2();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place,frag2);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager ft = getSupportFragmentManager();
if (ft.getBackStackEntryCount() > 0) {
ft.popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
if (action == KeyEvent.ACTION_UP) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_place);
if (f instanceof Fragment2) {
sendBroadcast();
}
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
private void sendBroadcast(){
Intent intent = new Intent("popup_menu");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}}
This is the problematic fragment. The error lines are basically the method showPopup
public class Fragment2 extends Fragment {
private String key;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, parent, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
new IntentFilter("popup_menu"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPopup(view);
}
};
public void showPopup(View v) {
Button b = (Button) view.findViewById(R.id.b_attach);
PopupMenu popup = new PopupMenu(getActivity(), b);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//dosomething
}
});
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_popup, popup.getMenu());
popup.show();
}}
this is the way i do and it works for me:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,new fragment() ).commit();
I solved the issue getting rid of sendbroadcast() and broadcastReceiver(), instead of that now I call showPopup() directly from the mainActivity when I need it.

Android: "onCreatedView" calls every time when going back and "setUserVisibleHint" is not called

In my android application I have a ViewPager and 5 fragments. I previously used viewPager.setCurrentItem() to navigate, but the requirement for navigation animation has changed; For an example in some fragments when a previous fragment is called, we were asked not to show going back (left to right animation), instead show the user their moving to the next fragment (right to left animation). For an example in some cases user has to insert the same data again and again so instead of creating new fragmnets for these, we re-used the existing ones we created- so when the viewPager.setCurrentItem() is calling a fragment in the back (ex: we are now in 20th fragment and we are calling 10th fragment) it goes back and shows left to right animation.
Now we are not using the viewPager.setCurrentItem() method to navigate, instead we use FragmentTransaction. However we did not remove the fragments from the ViewPager anyway, expecting to complete this with minimum work (we are at the end of project when this requirement appeared)
But when we use the FragmentTransaction we have a new issue now. When we come back the onCreateView of fragmnets are getting called all the time! This didn't happen when we were using viewPager.setCurrentItem(). Lot of our code which should run only once are in this onCreateView.
Another issue is setUserVisibleHint() is called only in first fragment and that is also only at the initial run! All of our code which should run every time the fragmnet is displayed is located in this method.
Below is an example code, which demonstrate our issue.
MainActivity.java
public class MainActivity extends FragmentActivity {
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager=(ViewPager)findViewById(R.id.viewPager);
viewPager.setAdapter(new MyPagerAdapter2(getSupportFragmentManager()));
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (viewPager.getCurrentItem() == 0) {
return true;
}
if (viewPager.getCurrentItem() == 1) {
return true;
}
if (viewPager.getCurrentItem() == 2) {
return true;
}
if (viewPager.getCurrentItem() == 3) {
return true;
}
if (viewPager.getCurrentItem() == 4) {
return true;
}
return false;
}
});
}
private class MyPagerAdapter2 extends FragmentPagerAdapter {
public MyPagerAdapter2(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment1.newInstance("FirstFragment_1");
case 1: return SecondFragment1.newInstance("SecondFragment_1");
case 2: return ThirdFragment1.newInstance("ThirdFragment_1");
case 3: return FourthFragment1.newInstance("FourthFragment_1");
case 4: return FifthFragment1.newInstance("FifthFragment_1");
default: return FirstFragment1.newInstance("DefaultFragment_1");
}
}
#Override
public int getCount() {
return 1;
}
}
public void setCurrentItem(int which) {
if(viewPager != null && which >= 0 && which <= 4) {
viewPager.setCurrentItem(which);
}
}
}
FirstFragment1.java
public class FirstFragment1 extends Fragment {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag_1, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText("FRAGMENT 01");
textView=(TextView)v.findViewById(R.id.textView1);
textView.setText("Fragment Name : - 01");
Log.d("FRAGMENT_01", "ON_CREATE");
Button button1 = (Button) v.findViewById(R.id.nextButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity() != null) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.firstFragment, new SecondFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return v;
}
public static FirstFragment1 newInstance(String text) {
FirstFragment1 f = new FirstFragment1();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Activity a = getActivity();
if (a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
// textView.setText("Fragment Name : - 01");
Log.d("FRAGMENT_01", "VISIBLE_HINT");
}
}
}
SecondFragment1.java
public class SecondFragment1 extends Fragment {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag_1, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
tv.setText("FRAGMENT 03");
textView=(TextView)v.findViewById(R.id.textView2);
textView.setText("Fragment Name : - 02");
Log.d("FRAGMENT_02", "ON_CREATE");
Button button=(Button)v.findViewById(R.id.printButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getActivity() != null) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.secondFrag, new FirstFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
Button button1=(Button)v.findViewById(R.id.nextButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity() != null) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.secondFrag, new ThirdFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return v;
}
public static SecondFragment1 newInstance(String text) {
SecondFragment1 f = new SecondFragment1();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
Log.d("FRAGMENT_02","VISIBLE_HINT");
}
}
}
As you can see in our code, we use below to navigate between Fragments. (Below code shows navigating from first fragmnet to second)
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.firstFragment, new SecondFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
Looking at our code, and considering we have added the ViewPager as well, how can we make sure that onCreateView is only called once and setUserVisibleHint is called everytime the fragment is displayed?
there is challenges when using setUserVisibleHint is called.try viewPager.setOffscreenPageLimit(5); and use setMenuVisibility method and if you launch app on any fragment by notification
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if(menuVisible && isResumed()){
// do your work here
}
if(!isResumed()){
// do your work when Activity is created
}
}
Put all of your code which you want should not be called everytime in onCreate() method and the code which you want should be called everytime in onCreateView() method.

Return to previously fragments

I am doing an Android app using fragments but i haven't previously experience with fragments.
I have a main FragmentActivity where i load a main view and i call my fragment class:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
FragmentTransaction FT = getFragmentManager().beginTransaction();
if (findViewById(R.id.fragmentAction) != null) {
FT.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), getApplicationContext()));
}
FT.addToBackStack(null);
FT.commit();
}
#Override
public void onBackPressed() {
}
And this is my fragmet classm where when i push button call to other fragment:
public class MainMenuFragment extends Fragment {
private static String my_description = "";
private static Context my_context = null;
public static MainMenuFragment newInstance(String description,
Context context) {
my_description = description;
my_context = context;
MainMenuFragment f = new MainMenuFragment();
return f;
}
public MainMenuFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = null;
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
view = inflater.inflate(R.layout.main_menu, container, false);
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (my_description.compareTo(getString(R.string.main_menu)) == 0) {
Button new_user = (Button) getView().findViewById(
R.id.button_newUser);
new_user.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction FT = getFragmentManager()
.beginTransaction();
FT.replace(R.id.fragmentAction, LdapFragment.newInstance(
getString(R.string.new_user), my_context));
FT.commit();
}
});
}
}
}
My question is: how can i do to return to previously fragment when i push back key? I add onBackPressed function in my FragmentActivity and capture the event, but what have i to do?
Use this code
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
}
public void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(
R.id.fragment_container);
setFragName("NONE");
if (currentFrag != null) {
setFragName(currentFrag.getClass().getSimpleName());
}
if (currentFrag != null) {
transaction.remove(currentFrag);
}
transaction.commit();
}
following is the code that i use. You need not do anything. Android system handles backpress and shows the appropriate fragment in the navigation order
#Override
public void onBackPressed() {
super.onBackPressed();
if (getFragmentManager().getBackStackEntryCount() == 0)
finish();
}
you missed the super.onBackPressed(); call. Try adding that to your code.
Just create method for add and back to fragment .
for example,
public void setFragment(Fragment fragment, boolean backStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
if (backStack) {
fragmentTransaction.addToBackStack(tag);
}
fragmentTransaction.replace(R.id.fragmentAction, MainMenuFragment.newInstance(
getString(R.string.main_menu), tag);
fragmentTransaction.commit();
}
call method from onCreate() or onResume()of your Activity.
setFragment(Your FragmentClass object, true, "tag");

Return to Fragment A from Fragment B with a value

I know there have been many threads about this, but i just cant seem to really understand how to nail it.. What i basically try to do is after button click in Fragment B i want to return to Fragment A together with a id value..
So in my BackStack you go to Fragment A which lead you to Fragment B and when pressing a button i want to go back to Fragment A with a value to show. This is my onClick listener in Fragment B:
//Fragment B which i called from Fragment A
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(value.getText().toString().trim().length() != 0) {
String order = value.getText().toString(); //The value i want in Fragment B
//return to Fragment A
}
}
In my MainActivity i tread my fragment like this:
//fragmentManager is initialized in onCreate()
...
private void selectItem(int position) {
Fragment fragment = null;
String fTag = null;
switch (position) {
case 0:
fragment = new FragmentA();
fTag = "fragmentA";
break;
case 1:
fragment = new FragmentC();
fTag = "fragmentC";
break;
case 2:
fragment = new FragmentD();
fTag = "fragmentD";
break;
default:
break;
}
if (fragment != null) {
if(replaceFragments(fragment, fTag)) {
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
} else {
Log.e(LOGTAG, "Error in creating fragment");
}
}
public boolean replaceFragments(Fragment fragment, String fTag) {
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, fTag).addToBackStack(fTag).commit();
return true;
}
#Override
public void onBackPressed() {
int count = fragmentManager.getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
//TODO: add app title on count == 1
}
}
Create interface ValueChangeListener.java
public interface ValueChangeListener {
public void onValueChanged(String value);
}
Pass the value via interface:
public class FragmentB extends Fragment {
private ValueChangeListener valueChangeListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
valueChangeListener = (ValueChangeListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement ValueChangeListener");
}
}
//your code
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(value.getText().toString().trim().length() != 0) {
String order = value.getText().toString();
//now the value is in the Activity and you can pass it anywhere you want from there
valueChangeListener.onValueChanged(order);
}
}
}
Implement interface to the activity:
public class YourActivity extends FragmentActivity implements ValueChangeListener{
#Override
public void onValueChanged(String value) {
//your value is here
}
}
Your onclick method should look like this:
#Override
public void onClick(View view) {
if(value.getText().toString().trim().length() != 0) {
String order = value.getText().toString(); //The value i want in Fragment B
//return to Fragment A
FragmentA fragment = new FragmentA();
Bundle args=new Bundle();
args.putString(order);
fragment.setArguments(args);
getFragmentManager().beginTransaction().replace((R.id.content_frame,fragment).commit();
}
And then from your FragmentA you can recover the value with:
getArguments();

Call parent fragment method from dialog fragment

I have a parent fragment, within this. Upon a button click, a child dialog fragment is getting created.
Now I would like to know how to call parent fragment function from child dialog fragment.
Here is the sample code :
/**SampleFragment.java**/
public class SampleFragment extends Fragment {
// Instantiate view & add event handlers
public void onButtonClick(....) {
// Create a dialog framgent
}
public void refreshView() {
}
}
/**SampleDialogFragment.java**/
public class SampleDialogFragment extends DialogFragment {
// Instantiate view for dialog
public void onButtonClick(...) {
// Call parent fragment method, i.e call refreshView() of SampleFragment
}
}
In a Fragment:
SampleDialogFragment dialogFragment = new SampleDialogFragment();
dialogFragment.show(getChildFragmentManager());
In a DialogFragment:
((SampleFragment) getParentFragment()).refreshView();
After calling this method, you can access public methods of a parent fragment.
In say your parent fragment, SettingsFragment for example. Note the setTargetFragment()
public void onButtonClick(....)
{
PrefLanguageDialogFragment prefLang = PrefLanguageDialogFragment.newInstance();
prefLang.setTargetFragment(SettingsFragment.this, 1337);
prefLang.show(getFragmentManager(), "dialog");
}
In our dialog, note the getTargetFragment()
SettingsFragment frag = (SettingsFragment)getTargetFragment();
if(frag != null){
frag.refreshSomething();
}
when you want add SampleFragment to your activity set it a tag, e.g "SampleFragment".
then
public void onButtonClick(...){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
SampleFragment parent = (SampleFragment)fm.findFragmentByTag("SampleFragment");
parent.refreshview();
}
have not test it but it may help:-)
The best way is to go for interface, declare an interface in nested fragment -
public interface checkingClickListener
{
public void checkingClickListener(String data);
}
then attach this interface to parent fragment -
public void onAttachFragment(Fragment fragment)
{
try
{
clickListener = (checkingClickListener) fragment;
} catch (ClassCastException e)
{
throw new ClassCastException(fragment.toString() + " must implement checkingClickListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
this.mContext = getActivity().getApplicationContext();
onAttachFragment(getParentFragment());
....
}
you need to call this listener on some button click -
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.tv_submit:
if (clickListener != null)
{
clickListener.checkingClickListener("sending data");
}
break;
}
}
Implement this interface in parent fragment -
public class Fragment_Parent extends Fragment implements Nested_Fragment.checkingClickListener
{
....
#Override
public void checkingClickListener(final List<Player> players_list)
{
FragmentManager fragmentManager = getChildFragmentManager();
SomeOtherNestFrag someOtherNestFrag = (SomeOtherNestFrag) fragmentManager.findFragmentByTag([Tag of your fragment which you should use when you add]);
if(someOtherNestFrag != null)
{
// your some other frag need to provide some data back based on views.
SomeData somedata = someOtherNestFrag.getSomeData();
// it can be a string, or int, or some custom java object.
}
}
}
Hope this helps you.

Categories