I want to change a ImageView in fragment(that create in code), from FragmentActivity. (there is no fragment and tag in XML).

MainActivity that extends from FragmentActivity and implements from GooglePlayServicesClient.ConnectionCallbacks:

...
FragmentAdapter mAdapter;
ViewPager mPager;
...

public void onCreate(Bundle savedInstanceState){
    ...
    FragmentManager fm = getSupportFragmentManager();
    mAdapter = new FragmentAdapter(fm);
    mPager.setAdapter(mAdapter);
    ...}

@Override
public void onConnected(Bundle connectionHint){
//*** I want to change a ImageView on Fragment1 here
}

FragmentAdapter that extends from FragmentPagerAdapter:

...
private FragmentManager mFragmentManager;

public FragmentAdapter(FragmentManager fm){
    super(fm);
}

@Override
public Fragment getItem(int pos){
// String name = makeFragmentName(R.id.mainPager, pos);
// Fragment fragmentObject = mFragmentManager.findFragmentByTag(name);
Fragment fragmentObject = null;

switch(pos){
    case 0:
        fragmentObject = new Fragment1();
        break;
    ...
}

return fragmentObject;
}
...

//private static String makeFragmentName(int viewId, iont index){
    //return "android:switcher:" + viewId + ":" + index;
//}

According to this topic for change a element in fragment, from fragmentActivity:

Fragment1 that extends from Fragment:

private ImageView IMGThisImageShouldChange = null;

public View onCreateView(...){
    IMGThisImageShouldChange = (ImageView)v.findViewById(R.id.TargetImage);
    ...
}

public void changeImageView(int resourceId){
    IMGThisImageShouldChange.setImageResource(resouirceId);
}

A comment line in this topic says:

//Do not create new object each time you set text. Use the same fragment object which you use for view pager.

So how can i access to fragmentObject from MainActivity, to call changeImageView method?

If i should find fragment via tag, according to this topic, where i should set tag and how to find?


So obviously adjust for your specific needs, but this is what I use for my Application.

 Fragment frag = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + mPager.getCurrentItem());
    if(frag!=null&&mPager.getCurrentItem()==0)
        {
           ((Fragment1) frag).changeImageView(1);
        }