سؤال

If I try to setText on a TextView in the onCreate() of an Activity, I always get a "Unfortunately, XXX has stopped." message.

I had previously avoided this being a necessity by doing any setText code in onStart(). At first I thought this was because you shouldn't setText a UI item in the onCreate() as it was not yet visible, but I don't think so now.

I think I now need to do setText in onCreate() as I want to use the savedInstanceState Bundle for screen orientation flipping.

I have the following code:

@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"));
    }
}

I was wondering if it is because I am using the Fragment created by Android Studio to hold my UI components. If so, do I need to place this test retrieval and setText code in the following method?

public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
    {
        View rootView = inflater.inflate (R.layout.fragment_hmc,container,false);

        return rootView;
    }

I see many other samples of code where people are using setText on UI components in the onCreate method of the Activity... most problems with this not working appear to be related to not using setContentView or not using findViewById before calling setText - but you can see I am doing both of those, hopefully correctly.

So - if I am using a Fragment to hold my UI components, does this mean I cannot use setText on those UI components in the Activity's onCreate() method?

Many thanks for helping me understand this better... once taught I'll remember forever.

هل كانت مفيدة؟

المحلول

You have to initialize your TextView in onCreateView, and with rootView. So, your code should look like this:

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;
}

And remove your initialization from MainActivity ;)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top