Monday, January 12, 2015

How to set Button background to transparent programmatically in Android

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="left"
    android:layout_margin="15dp"
    android:background="#87CEEB"
    tools:context=".MainActivity"
    >
    <Button
        android:id ="@+id/push_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click To Transparent The Button Background"
        android:padding="15dp"
        android:onClick="perform_action"
        />
</LinearLayout>
MainActivity.java code snippet

public void perform_action(View v)
{
 Button btn = (Button) findViewById(R.id.push_button);
 //apply the button background full transparent
 btn.getBackground().setAlpha(0);
}
Imported Class

import android.view.View;
import android.widget.Button;
More android examples