Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio: Button always appears at the front

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?

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);
}
like image 675
Maxim Laco Avatar asked Apr 27 '15 21:04

Maxim Laco


2 Answers

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?

like image 96
honeal Avatar answered Nov 15 '22 19:11

honeal


In the Android 5.0 (API 21) and above, you must add android:elevation into the view.

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);
}
like image 22
Khoa Vo Avatar answered Nov 15 '22 21:11

Khoa Vo