Android - 通过Activity访问片段组件

时间:2014-11-22 00:41:51

标签: android android-layout android-fragments fragment

我有一个简单的问题,不需要我展示我的任何编码。我有1个片段活动活动和3个片段,它们是标签。这些选项卡包含ImageView,TextView等组件。

有没有办法从Fragment Activity访问这些组件?我必须在那里使用它们并从Fragment Activity中分配它们的图像等。

感谢。

1 个答案:

答案 0 :(得分:0)

您应该通过这种方式在活动中加载片段:

MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

并在 MyFragment 中,您应该实现一个返回所需数据的方法,如下所示:

public class MyFragment extends Fragment {
    ...
    TextView mTextView;
    ImageView mImageView;
    ...

    public ImageView getImageView() {
        return mImageView;
    }

    public TextView getTextView() {
        return mTextView;
    }

    ...
}

并在您的活动中调用以下方法:

 TextView fragmentTextView = fragment.getTextView();
 ImageView fragmentImageView = fragment.getImageView();