Android “Only the original thread that created a view hierarchy can touch its views.”

后端 未结 28 3301
鱼传尺愫
鱼传尺愫 2020-11-21 04:44

I\'ve built a simple music player in Android. The view for each song contains a SeekBar, implemented like this:

public class Song extends Activity implement         


        
28条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 05:27

    This is the stack trace of mentioned exception

            at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6149)
            at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:843)
            at android.view.View.requestLayout(View.java:16474)
            at android.view.View.requestLayout(View.java:16474)
            at android.view.View.requestLayout(View.java:16474)
            at android.view.View.requestLayout(View.java:16474)
            at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
            at android.view.View.requestLayout(View.java:16474)
            at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
            at android.view.View.setFlags(View.java:8938)
            at android.view.View.setVisibility(View.java:6066)
    

    So if you go and dig then you come to know

    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
    

    Where mThread is initialize in constructor like below

    mThread = Thread.currentThread();
    

    All I mean to say that when we created particular view we created it on UI Thread and later try to modifying in a Worker Thread.

    We can verify it via below code snippet

    Thread.currentThread().getName()
    

    when we inflate layout and later where you are getting exception.

提交回复
热议问题