Android(Fragment)-是否建议在onActivityCreated方法内初始化视图对象? [英] Android(Fragment) - Is it recommended to initialize a view object inside onActivityCreated method?

查看:243
本文介绍了Android(Fragment)-是否建议在onActivityCreated方法内初始化视图对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

View变量可以用onCreateView方法初始化,这里TextView在片段内部.

View variables of fragments can be initialised in onCreateViewmethod in this way.Here the TextView is inside the fragment.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmant_two,container,false);
    if(savedInstanceState == null)
    {

    }
    else
    {
        String data = savedInstanceState.getString("data");
        TextView myText = (TextView)view.findViewById(R.id.text_view);
        myText.setText(data);
    }


    return view;


}

但是我发现以这种方式在onActivityCreated内部初始化了一个视图.

But I found that a view is initialized inside onActivityCreated in this way.

textView = (TextView) getActivity().findViewById(R.id.text_view);

有什么理由我应该选择onActivityCreated而不是onCreateView吗?

is there any reason for which I should choose onActivityCreated over onCreateView ?

推荐答案

textView = (TextView) getActivity().findViewById(R.id.text_view);

这将尝试从活动而不是片段的布局中查找ID为R.id.text_view的视图.如果片段本身中包含具有该ID的视图,则应在片段中使用onCreateView方法.

This will try to find the view with id R.id.text_view from the layout of your activity, not your fragment. If the view with that id is present in your fragment itself then you should use the onCreateView method within your fragment.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmant_two,container,false);
    TextView textView = (TextView) view.findViewById(R.id.text_view);
    // bind your data here.
    return view;
}

这篇关于Android(Fragment)-是否建议在onActivityCreated方法内初始化视图对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆