从Fragment对象访问FragmentActivity中的元素

e-n*_*ure 2 android swipe android-fragments fragmentpageradapter

我有一个FragmentActivity和FragmentPagerAdapter,它包含许多Fragment对象,我可以通过水平滑动来滑动它们.

我想知道我是否可以从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);

}
}
Run Code Online (Sandbox Code Playgroud)

我怎么会这样做?每当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;
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 10

在您的GalleryPagerActivity中创建一个函数,如updateTextView(String text).该函数将设置TextView为输入值.然后在您的GalleryFragment中,只需调用此函数,并将文本显示为:

    ((GalleryPagerActivity)getActivity()).updateTextView("my text");
Run Code Online (Sandbox Code Playgroud)