How To Create Rounded Corner Layout in Android

Rounded Corner Layout in Android Thumb

24th February, 2020

Howdy Android developer!

In this tutorial you will know that how to create rounded corners layout programmatically.

Step 1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 2: Create custom View

Create a view as follows.

package com.codestringz.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.FrameLayout;

public class RoundCornerLayout extends FrameLayout
{
    private float CORNER_RADIUS = 50.f;
    private float mCornerRadius;
    private Paint mPaint;
    private Paint mMaskPaint;
    private DisplayMetrics mMetrics;

    public RoundCornerLayout(@NonNull Context context)
    {
        super(context);
        init(context);
    }

    public RoundCornerLayout(@NonNull Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs, 0);

        init(context);
    }

    public RoundCornerLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context)
    {
        mMetrics = context.getResources().getDisplayMetrics();

        mCornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, mMetrics);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        mMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mMaskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

        setWillNotDraw(false);
    }

    @Override
    public void draw(Canvas canvas)
    {
        if (isInEditMode())
        {
            /*
              If you don't use this if clause, 
              Android Studio's layout preview window will not showing anything!!!
             */
            super.draw(canvas);
        }

        Bitmap offscreenBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);

        Canvas offscreenCanvas = new Canvas(offscreenBitmap);

        super.draw(offscreenCanvas);

        Bitmap maskBitmap = createMask(getWidth(), getHeight());
        if (maskBitmap != null)
        {
            offscreenCanvas.drawBitmap(maskBitmap, 0f, 0f, mMaskPaint);
            canvas.drawBitmap(offscreenBitmap, 0f, 0f, mPaint);
        }

    }

    private Bitmap createMask(int width, int height)
    {
        Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
        Canvas tempCanvas = new Canvas(mask);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);

        tempCanvas.drawRect(0, 0, width, height, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        tempCanvas.drawRoundRect(new RectF(0, 0, width, height), mCornerRadius, mCornerRadius, paint);

        return mask;
    }

    public void setCornerRadius(float myCornerRadius)
    {
        CORNER_RADIUS = myCornerRadius;
        mCornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, mMetrics);
        this.invalidate();
    }
}

Step 3: Add View to Layout XML

Change the respective layout file as follows.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="5dp"
    tools:context=".MainActivity">

    <com.codestringz.view.RoundCornerLayout
        android:id="@+id/myRoundCornerLayout"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:background="#F50057"/>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_margin="10dp"
        android:background="#00B0FF"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Corner"
            android:textColor="#FFFFFF" />

        <SeekBar
            android:id="@+id/seekBar1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:max="100"
            android:progress="20" />
    </LinearLayout>
</RelativeLayout>

Step 4: Modify Your Activity

Finally, You will have to add custom layout control code in the activity. Change your activity as follows and run your app.

package com.codestringz.roundedLayoutTest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;

import com.codestringz.view.RoundCornerLayout;

public class MainActivity extends AppCompatActivity
{
    private RoundCornerLayout mRoundCornerLayout;

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

        setUIRef();
    }

    private void setUIRef()
    {
        mRoundCornerLayout = findViewById(R.id.myRoundCornerLayout);

        SeekBar seekBar = findViewById(R.id.seekBar1);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        {
            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser)
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mRoundCornerLayout.setCornerRadius(progress);
                    }
                });
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar){}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar){}
        });
    }
}

Happy coding!

Leave a Reply