B
B
BitNeBolt2020-02-13 18:03:13
Android
BitNeBolt, 2020-02-13 18:03:13

Why can't you access the elements of a fragment immediately after adding it?

When starting a new activity, I need to add a fragment, and in it change the text of the TextView. Why does the program crash on the next. code block? If you put it in a separate onClick() method (then you can’t change the value at startup), then everything works and the text changes.

What is the reason for this and are there other ways to get the contents of a fragment?

Here is the piece of code that doesn't work:

FragmentManager manager = getSupportFragmentManager();

FragmentTransaction transaction = manager.beginTransaction();
TextFragment text_fragment = new TextFragment();

transaction.add(R.id.fragment_layout, text_fragment);
transaction.commit();

Fragment test_one = manager.findFragmentById(R.id.fragment_layout);
((TextView) test_one.getView().findViewById(R.id.sentence)).setText("dsadasd");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-02-13
@BitNeBolt

Because transaction commit is asynchronous. When you made it, the fragment was added not at once. You can do commitNow or executePendingTransactions.
But in any case, this is wrong, the fragment view is its own business, it should be encapsulated in it and should not twitch outside.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question