我有一个带有控件(TextView)的片段,其ID为R.id.currentCycleIndicator
,我想在片段内部以编程方式设置其值。
但是,
getActivity().findViewById(R.id.currentCycleIndicator)
getView().findViewById(R.id.currentCycleIndicator)
都会返回null。
我该如何在片段代码中引用该TextView?
我有一个带有控件(TextView)的片段,其ID为R.id.currentCycleIndicator
,我想在片段内部以编程方式设置其值。
但是,
getActivity().findViewById(R.id.currentCycleIndicator)
getView().findViewById(R.id.currentCycleIndicator)
都会返回null。
我该如何在片段代码中引用该TextView?
尝试在Fragment的onCreateView()回调函数中获取其值,如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
TextView textView = (TextView) view.findViewById(R.id.currentCycleIndicator);
return view;
}
private TextView tv;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.currentCycleIndicator);
}
onCreateView
中展开您的视图,并从那里引用您的TextView。@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layoutwheretextviewis, container, false);
TextView text= (TextView) view.findViewById(R.id.currentCycleIndicator);
return view;
}