2

我有一个带有 FragmentPagerAdapter 的 FragmentActivity,它包含许多 Fragment 对象,我可以通过水平滑动滑动这些对象。

我想知道是否可以从 Fragment 对象中访问 FragmentActivity 中的元素(“elementToBeChanged”)?我想将 Fragment 类中的字符串传递给 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;
}
4

1 回答 1

10

In your GalleryPagerActivity create a function such as updateTextView(String text). That function will set the TextView to whatever the input value is. Then in your GalleryFragment simply call this function with the text to be displayed as such:

    ((GalleryPagerActivity)getActivity()).updateTextView("my text");
于 2012-02-22T21:06:29.570 回答