android - 如何在UI中同时编辑EditText和TextView

标签 android multithreading textview android-edittext

我正在实现一个简单的聊天应用程序,它有一个用于文本消息的 TextView 和一个用于输入的 EditText。 我通过以下方法更新我的 TextView:

    private void addChatContent(String authorName, String content){
    final String newLine = authorName+" : "+content+"\n";
    chat_content.append(newLine);
    scroll.post(new Runnable(){
        @Override
        public void run() {
            scroll.smoothScrollTo(0, chat_content.getBottom()+5000);
        }
    });
}

我面临的一个问题是:当有新的传入消息时,UI 线程将忙于刷新 TextView。它使我的 EditText 变得滞后,我几乎无法编辑我的输入。 我不能用另一个线程刷新 TextView,对吗? 那么我应该怎么做才能克服这个限制呢? 有人能给我点亮吗?提前致谢。

最佳答案

最终,不幸的是,只有一个线程专用于 UI。如果您要更新 TextView,则无法同时获得 EditText 的无延迟体验。你已经知道这一点,但我担心有些人回答这个问题可能不知道,所以 here's a reference :

The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process

...

When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events.

...

Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:

Do not block the UI thread Do not access the Android UI toolkit from outside the UI thread

因此,答案很明确:不要这样做。为什么 Textview 必须绝对 100% 最新,因为用户正在更新 EditText 字段?你为什么一直滚动到底部?也许您可以删除 TextView 的大部分内容并在用户滚动时动态地重新添加内容?

IMO 你应该专注于减少你需要在 TextView 上做的工作量。

关于android - 如何在UI中同时编辑EditText和TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7514245/

相关文章:

c# - 在浏览器中打开 URL 并更改应用程序 View - Android Xamarin

android - 更改 SearchView 小放大镜图标

java - Thread.holdsLock() 和锁粗化

Java - 在对象上调用 wait() 然后允许对象访问方法

java - 每次用户单击 EditText 上的按钮时添加 Double

java - 设备旋转导致 Activity 被销毁和创建

android - 将 ScrollView 添加到 RelativeLayout 会更改小部件的位置

c - 线程终止后内存映射对象会自动释放吗?

android - 文本覆盖在android中的imageview上

android - 来自 Html 粗体标记的 Textview 未正确显示