Android scrolls down after adding a new fragment

I have an application with LinearLayout, with which rectangular fragments are added under each other with time from top to bottom.

At some point, the screen is full, and new fragments are β€œhidden” outside the screen. What I would like to do is scroll down the application each time a new snippet is added.

A fragment is added each time a button in action is pressed or a checkmark is selected in the fragment indicated above. So I tried the following in onClickListeners and in onCreateView snippets:

fm.beginTransaction().add(R.id.activity_uhf_layout, fragment).commit(); //Adding fragment runOnUiThread(new Runnable() { @Override public void run() { scrollView.scrollTo(0, scrollView.getBottom()); }}); 

This sometimes works, a fragment is added, and the screen scrolls down, but it is like 1/8 times.

I tried other things such as:

  scrollView.post(new Runnable() { @Override public void run() { scrollView.scrollTo(0, scrollView.getBottom()); } }); 

Which basically gives the same result, and I tried without a Runnable message, which doesn't work at all.

The result that I get is that the layout only scrolls to the bottom of the fragment that is already present, and not all the way to the end of the new fragment that has just been added using the managermanager.

It seems to me that even if a fragment is added, the LayoutManager did not actually "detect" it or something like that, but how to get around it, I'm not quite sure.

+6
source share
1 answer

You can also try to do this.

 fm.executePendingTransactions(); runOnUiThread(new Runnable() { @Override public void run() { //Linearlayout is the layout the fragments are being added to. View view = linearLayout.getChildAt(linearLayout.getChildCount()-1); scrollView.scrollTo(0, view.getY() + view.getHeight()); }}); 

I do not know that executePendingTransactions () is necessary, but if a view has been added, then this should work.

0
source

Source: https://habr.com/ru/post/987112/


All Articles