Android Studio:按钮始终显示在前面



我有一个 RelativeLayout,我在其中添加了视图。

我向其添加了一个按钮,该按钮始终显示在添加到其中的所有其他视图的前面,无论添加内容的顺序如何。怎么来了?

我纯粹用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);
}

从棒棒糖开始,控制提升的 StateListAnimator 被添加到默认的按钮样式中。根据我的经验,这迫使按钮出现在其他所有内容之上,而不管在 XML 中的位置如何(或在您的情况下是编程添加)。这可能就是你正在经历的。

要解决此问题,如果需要,

您可以添加自定义状态列表动画器,或者如果您不需要,只需将其设置为 null。

.XML:

android:stateListAnimator="@null"

爪哇岛:

Button button = new Button(this);
button.setText("Button");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    button.setStateListAnimator(null);
}

更多详情:Android 5.0 安卓:elevation 适用于视图,但不适用于按钮?

在 Android 5.0 (API 21) 及更高版本中,您必须将 android:elevation 添加到视图中。

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");
    button.setElevation(3.0f); // add this line, you could try with values > 3.0f
    layout.addView(button);
    layout.addView(text);
    setContentView(layout);
}

来自安卓开发者文档:

By default, all child views are drawn at the top-left of the layout, so you must define the position of each view using the various layout properties available from RelativeLayout.LayoutParams.

http://developer.android.com/guide/topics/ui/layout/relative.html

尝试以下代码片段:

RelativeLayout layout = new RelativeLayout(this);
        Button button = new Button(this);
        TextView text = new TextView(this);
        button.setId(View.generateViewId());
        text.setId(View.generateViewId());
        button.setText("Button");
        text.setText("Text");
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, text.getId());
        button.setLayoutParams(params);
        layout.addView(button);
        layout.addView(text);

该按钮似乎浮动到它所在的相对布局的最前面,所以...

试试这个:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button button = new Button(this);
    button.setText("Button");
    RelativeLayout groupContainingButton = new RelativeLayout(this);
    groupContainingButton.addView(button);
    TextView text = new TextView(this);
    text.setText("Text");
    RelativeLayout activityLayout = new RelativeLayout(this);
    activityLayout.addView(groupContainingButton);
    activityLayout.addView(text);
    setContentView(activityLayout);
}

检查按钮的状态(启用/禁用):

loginButton.setEnabled(false);

最新更新