简体   繁体   中英

How can I get a Flex container to scroll to the last position?

I'm creating a chat window, much like this example

http://demo.seanhess.net/oneshots/scrolling.swf

Whenever a chat is added, I want it to completely show the last message. I'm using maxVerticalScrollPosition to set the scroll position on the list, but it is always wrong (see the example). It undershoots it by a row or so. I've tried this with a regular container and it does the same thing. If I do maxVerticalScrollPosition+1, it sort of works, but if the last message is particularly long, it will be cut off (only show the top).

How can I get it to scroll to the actual bottom of the container??

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:Script>
        <![CDATA[
            protected function addChat():void
            {
                collection.addItem(new String(input.text));
                list.verticalScrollPosition = list.maxVerticalScrollPosition;
                input.text = "";
            }
        ]]>
    </mx:Script>

    <mx:Panel width="400" height="290">
        <mx:List id="list" width="100%" height="100%" variableRowHeight="true">
            <mx:dataProvider>
                <mx:ArrayCollection id="collection"/>
            </mx:dataProvider>
            <mx:itemRenderer>
                <mx:Component>
                    <mx:Text text="{data}"/>
                </mx:Component>
            </mx:itemRenderer>
        </mx:List>
        <mx:HBox width="100%">
            <mx:TextInput id="input" width="100%" enter="addChat()"/>
            <mx:Button label="add" click="addChat()"/>
        </mx:HBox>
    </mx:Panel>
</mx:Application>

Separate addChat() into two functions, addChat() and addChatScrollToEnd(). Add the chat item within addChat() and then callLater(addChatScrollToEnd) which would have the scroll lines.

Alternatively you can call list.validateNow() but it's not recommended for performance reasons.

This should work for you.

    <mx:Script>
            <![CDATA[
                    protected function addChat():void
                    {
                            collection.addItem(new String(input.text));
                            callLater(function() {
                                    list.verticalScrollPosition = list.maxVerticalScrollPosition;
                            });
                            input.text = "";
                    }
            ]]>
    </mx:Script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM