Android Studio:按钮总是出现在前面 [英] Android Studio: Button always appears at the front

查看:33
本文介绍了Android Studio:按钮总是出现在前面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向其添加视图的相对布局.

I have a RelativeLayout to which I add Views.

我给它添加了一个按钮,这个按钮总是出现在所有其他添加到它的视图之前,不管添加的顺序如何.怎么来的?

I added a button to it, and the button always appears in front of all the other Views that are added to it, regardless of the order in which things were added. How come?

我纯粹用 Java 编写代码,没有使用 XML.

I'm coding purely in Java, no XML.

这是一个简单的例子,按钮会出现在文本的前面,即使文本是最后添加的:

Here's a simple example, the button will appear here in front of the text, even though the text was added last:

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 中的位置如何(或在您的情况下以编程方式添加),这都会强制按钮显示在其他所有内容之上.这可能就是您遇到的情况.

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.

要解决此问题,您可以在需要时添加自定义 StateListAnimator,如果不需要,只需将其设置为 null.

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);
}

更多详情:Android 5.0 android:elevation 适用于查看,但不是按钮?

这篇关于Android Studio:按钮总是出现在前面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆