[英]Trying to understand Android setText in onCreate of Activity with Fragment
如果我嘗試在Activity的onCreate()中的TextView上設置setText,那么我總是會收到“不幸的是,XXX已停止。” 信息。
我以前通過在onStart()中執行任何setText代碼來避免這種情況的發生。 起初,我認為這是因為您不應該在onCreate()中對UI項進行setText設置,因為它尚不可見,但我現在不這么認為。
我想我現在需要在onCreate()中執行setText,因為我想使用savedInstanceState Bundle進行屏幕方向翻轉。
我有以下代碼:
@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_hmc);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add (R.id.container,new PlaceholderFragment()).commit();
}
else
{
// This line works, I see a Toast and the data from "output" is displayed.
ShowToast (savedInstanceState.getString ("output"));
// This line also executes without causing any issue.
TextView tvOutput = (TextView) findViewById (R.id.textView4);
// This line causes a "Unfortunately, XXX has stopped" error message.
tvOutput.setText (savedInstanceState.getString ("output"));
}
}
我想知道是否是因為我使用的是Android Studio創建的片段來保存我的UI組件。 如果是這樣,是否需要在以下方法中放置此測試檢索和setText代碼?
public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate (R.layout.fragment_hmc,container,false);
return rootView;
}
我看到許多其他代碼示例,其中的人們在Activity的onCreate方法中的UI組件上使用setText……大多數與此不起作用的問題似乎與在調用setText之前不使用setContentView或不使用findViewById有關,但是您可以看到我正在做這兩個,希望正確。
所以-如果我使用Fragment來保存UI組件,這是否意味着我無法在Activity的onCreate()方法中的那些UI組件上使用setText?
非常感謝您幫助我更好地理解了這一點...一旦教過,我將永遠記住。
您必須在onCreateView和rootView中初始化TextView。 因此,您的代碼應如下所示:
public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate (R.layout.fragment_hmc,container,false);
TextView tvOutput = (TextView) rootView.findViewById (R.id.textView4);
tvOutput.setText (savedInstanceState.getString ("output"));
return rootView;
}
並從MainActivity中刪除您的初始化;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.