Sunday, October 30, 2016

android - Circular Button shadow

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b9cdf1"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Circular Button\nShadow"
        android:layout_gravity="center"
        android:padding="50dp"
        android:background="@drawable/circular_button_shadow"
        />
</android.support.design.widget.CoordinatorLayout>
res/drawable/circular_button_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#0e165c"/>
        </shape>
    </item>
    <item android:bottom="5dp" android:right="3dp">
        <shape android:shape="oval">
            <solid android:color="#fff"/>
            <gradient
                android:startColor="#5f69ff"
                android:endColor="#9298fc"
                android:angle="90"
                />
            <stroke android:color="#1a29ae" android:width="3dp"/>
        </shape>
    </item>
</layer-list>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private TextView mTextView;
    private Button mButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mButton = (Button) findViewById(R.id.btn);

        // Get the button widget width and height
        mButton.measure(0,0);
        int height = mButton.getMeasuredHeight();
        int width = mButton.getMeasuredWidth();

        // Make the button width and height same as widest side length
        if(height > width){
            mButton.getLayoutParams().width = height;
        }else {
            mButton.getLayoutParams().height = width;
        }
    }
}