Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

android - refresh fragment UI from fragmentActivity

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...