Android(Fragment)-是否建议在onActivityCreated方法内初始化视图对象? [英] Android(Fragment) - Is it recommended to initialize a view object inside onActivityCreated method?
问题描述
View
变量可以用onCreateView
方法初始化,这里TextView
在片段内部.
View
variables of fragments can be initialised in onCreateView
method 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屋!