如上面的布局所示,在5.0以上和5.0以下會有不同的效果:
可以看到,Button跑到了最上面,這是為毛啊?沒找到答案,但找到了不是辦法的解決辦法,就是在Button上包一層布局即可。
后續。。
在Stack Overflow上找到了答案:
Starting with Lollipop, a StateListAnimator controlling elevation was added to the default Button style. In my experience, this forces buttons to appear above everything else regardless of placement in XML (or programmatic addition in your case). That might be what you're experiencing.
To resolve this you can add a custom StateListAnimator if you need it or simply set it to null if you don't.
XML:
android:stateListAnimator="@null"
Java:
Button button = new Button(this); button.setText("Button"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { button.setStateListAnimator(null); }
More details: Android 5.0 android:elevation Works for View, but not Button?
也就是說在5.0以上,系統會在button上wrapper上一層效果,就是StateListAnimator。去掉它或者自定義一個就可以解決上述問題。