我有一个相对布局,我向其中添加视图。
我向其中添加了一个按钮,该按钮始终显示在添加到其中的所有其他视图的前面,无论添加内容的顺序如何。怎么会?
我纯粹使用 Java 编写代码,没有使用 XML。
这是一个简单的示例,即使文本是最后添加的,按钮也会出现在文本前面:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
Button button = new Button(this);
TextView text = new TextView(this);
button.setText("Button");
text.setText("Text");
layout.addView(button);
layout.addView(text);
setContentView(layout);
}
从 Lollipop 开始,控制高度的 StateListAnimator 被添加到默认的 Button 样式中。根据我的经验,这会强制按钮显示在其他所有内容之上,无论其在 XML 中的位置如何(或在您的情况下以编程方式添加)。这可能就是你正在经历的。
要解决此问题,您可以添加自定义 StateListAnimator(如果需要),或者只需将其设置为 null(如果不需要)。
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);
}
更多细节:Android 5.0 android:elevation 适用于 View,但不适用于 Button? https://stackoverflow.com/questions/27080338/android-5-0-androidelevation-works-for-view-but-not-button/27112143#27112143
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)