Android传递View作为片段的对象

时间:2016-07-01 11:11:41

标签: android android-fragments

我更google搜索如何将简单view作为对象传递给片段,但我不能。

例如在MainActivity中我有简单的视图:

TextView text = (TextView) findviewById(R.id.tv_text);

现在我想把它传递给片段。以下代码是我在MainActivity上的附加片段

MainActivity

public void attachFragment() {
    fts = getActivity().getFragmentManager().beginTransaction();
    mFragment = new FragmentMarketDetail();
    fts.replace(R.id.cardsLine, mFragment, "FragmentMarketDetail");
    fts.commit();
}

这是我的Fragment

public class FragmentMarketDetail extends Fragment implements ObservableScrollViewCallbacks {
    public static final String SCROLLVIEW_STATE = "scrollviewState";
    private ObservableScrollView scrollViewTest;
    private Context    context;
    private int scrollY;

    public static FragmentMarketDetail newInstance() {
        FragmentMarketDetail fragmentFirst = new FragmentMarketDetail();
        return fragmentFirst;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_online_categories, container, false);
        scrollViewTest = (ObservableScrollView) view.findViewById(R.id.scrollViewTest);
        scrollViewTest.setScrollViewCallbacks(this);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity().getBaseContext();
    }
}

3 个答案:

答案 0 :(得分:5)

以这种方式传递视图不是一个好习惯。如果要从片段类中访问活动中的视图,请使用getActivity()访问片段所附加的活动,然后从那里找到TextView。

TextView text = (TextView) getActivity().findViewById(R.id.tv_text);

答案 1 :(得分:1)

按标签查找片段并在其上调用一个函数:

mFragment = (FragmentMarketDetail ) getActivity().getFragmentManager().findFragmentByTag(FragmentMarketDetail .class.getSimpleName());
mFragment.passTextView(textView);

当然必须将片段添加到backstack中。

答案 2 :(得分:1)

如何在自定义片段中添加set函数 e.g。

public void setTextView(TextView tv){
    this.tv = tv
}

然后在

之后调用它
mFragment = new FragmentMarketDetail();
mFragment.setTextView(textView)