【发布时间】:2014-04-27 03:27:05
【问题描述】:
我有一个从其他活动接收数据的活动。此数据必须在活动中膨胀的片段中的 TextView 中显示。所以,代码是:
public class DetailActivity extends Activity {
private int idEstablecimiento;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit(); //Here the fragment is added to the activity
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
idEstablecimiento = extras.getInt("idEstablecimiento");
}
TextView textView = (TextView) this.findViewById(R.id.nombreView); //Declared in fragmentDetail, which has been already inflated at this point, but still null
textView.setText(this.idEstablecimiento);
}
//...
//Non related stuff...
//...
public static class PlaceholderFragment extends Fragment {
private int idEstablecimiento;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail,
container, false);
return rootView;
}
}
问题是onCreate()方法中的textView为null,如果fragment已经膨胀了,为什么会出现这种情况?一旦片段在 onCreate() 方法中膨胀,我不应该能够访问 IU 元素吗?或者如果没有,访问它的正确方法是什么?
【问题讨论】: