问题描述
我想改变片段的ImageView(即创建在code),从FragmentActivity。 (没有在任何XML片段标记)。
I want to change a ImageView in fragment(that create in code), from FragmentActivity. (there is no fragment and tag in XML).
MainActivity从FragmentActivity扩展,并实现从GooglePlayServicesClient.ConnectionCallbacks:
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从FragmentPagerAdapter扩展:
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;
//}
据this主题改变片段的元素,从fragmentActivity:
According to this topic for change a element in fragment, from fragmentActivity:
片段1,从片段扩展:
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:
//不要创建新的对象,每次设置文本的时间。使用相同的 您所使用的视图寻呼机片段对象。
那么如何从MainActivity访问fragmentObject,调用changeImageView方法?
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);
}
这篇关于刷新从fragmentActivity片段UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!