我有一個從其他活動接收數據的活動。該數據必須在活動中的一個片段中的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的是空,爲什麼會這樣,如果該片段已被誇大?一旦片段在onCreate()方法中膨脹後,我不應該能夠訪問IU元素嗎?或者,如果沒有,訪問它的方法是什麼?
我認爲這是不超載的片段構造一個好主意:http://stackoverflow.com/questions/11602433/fragment-newinstance-vc-onsaveinstancestate/11602478# 11602478但無論如何非常感謝,非常有用 – moictab