2012-02-22 41 views
2

我有一个FragmentPagerAdapter,它包含大量Fragment对象,通过它我可以通过水平滑动进行滑动。从Fragment对象访问FragmentActivity中的元素

我想知道如果我可以在Fragment对象内访问FragmentActivity中的元素(“elementToBeChanged”)吗?我想从Fragment类传递一个String到FragmentActivity对象中的TextView元素。

public class GalleryPagerActivity extends FragmentActivity implements OnClickListener { 

private TextView elementToBeChanged; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    super.setContentView(R.layout.gallery_pager); 

    elementToBeChanged = (TextView) findViewById(R.id.tvTop); 
    elementToBeChanged.setOnClickListener(this); 

} 
} 

我该怎么做?每次看到Fragment对象时(通过滑动),TextView元素都必须更新。

它应该是这个样子:

public class GalleryFragment extends Fragment { 

private FragmentActivity fa; 
private LinearLayout ll; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    fa = super.getActivity(); 

    ll = (LinearLayout) inflater.inflate(R.layout.gallery_fragment, container, false); 
... 
// //////// 
// UPDATE THE "TextView elementToBeChanged" object in the parent FragmentActivity class HERE WHENEVER THIS FRAGMENTS BECOMES ACTIVE/VISIBLE... 
// //////// 

    return ll; 
} 

回答

10

在你GalleryPagerActivity创建一个函数,如updateTextView(字符串文本)。该函数将设置TextView为任何输入值。然后在你的GalleryFragment中简单地调用这个函数以显示文本:

((GalleryPagerActivity)getActivity()).updateTextView("my text"); 
+0

谢谢!这很好用! – 2012-02-23 01:58:02

+0

我能为相反的情况做些什么?我想从fragmentActivity更新片段中的元素。我跟着这个链接:http://stackoverflow.com/questions/18486952/get-id-of-textview-in-fragment-from-fragmentactivity-in-viewpager ;;;;;;但他们表示:“每次设置文本时都不要创建新对象,请使用您用于查看传呼机的相同片段对象。”我如何访问该fragmentObject?所以我跟着这个链接:http://stackoverflow.com/questions/14035090/how-to-get-existing-fragments-when-using-fragmentpageradapter ;;;;;但我现在不知道该怎么办! – 2014-07-18 19:23:50

+0

请参阅我的相关问题:http://stackoverflow.com/questions/24833912/refresh-fragment-ui-from-fragmentactivity – 2014-07-19 07:45:12