【发布时间】:2014-02-06 17:47:25
【问题描述】:
如果我尝试在 Activity 的 onCreate() 中的 TextView 上设置文本,我总是会收到“不幸的是,XXX 已停止”。消息。
我以前通过在 onStart() 中执行任何 setText 代码来避免这种情况。一开始我以为这是因为你不应该在 onCreate() 中设置一个 UI 项,因为它还不可见,但我现在不这么认为了。
我想我现在需要在 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 创建的 Fragment 来保存我的 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?
非常感谢您帮助我更好地理解这一点...一旦教过我就会永远记住。
【问题讨论】:
-
发布您的日志猫。
tvOutput可能为空。
标签: android fragment oncreate settext