articles

Home / DeveloperSection / Articles / Creating custom and compound Views in Android

Creating custom and compound Views in Android

Manoj Pandey4763 13-Feb-2015

In my previous post, we have implemented multiple deletion in android :  Android Delete Multiple Selected Items in ListviewIn this post we are going to learn custom and compound views

The Android framework provides several default views but developer can also create their custom views and use them in their application.

You can make your control according to your need.  By extending the View class or one of its subclasses you can create your custom view.

Compound views also allow you to add custom API to update and query the state of the compound view.

1.      Create a demo Project

2.      Create n new class for create vertical button and paste following code

3.      In Main activity class

 

package com.example.customviewexample; 

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

 

public class MainActivity extends Activity {

            Button btnFirst, btnSecond; 

            @Override

            protected void onCreate(Bundle savedInstanceState) {

                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_main);

                        btnFirst = (Button) findViewById(R.id.firstButton);

                        btnSecond = (Button) findViewById(R.id.secondButton);

                        btnFirst.setOnClickListener(new OnClickListener() { 

                                    @Override

                                    public void onClick(View v) {

                                                // TODO Auto-generated method stub

                                                // Show toast message on First button click

                                                Toast.makeText(getApplicationContext(), "First Button Action",

                                                                        Toast.LENGTH_SHORT).show();

 

                                    }

                        });

                        btnSecond.setOnClickListener(new OnClickListener() { 

                                    @Override

                                    public void onClick(View v) {

                                                // TODO Auto-generated method stub

                                                // Show toast message on Second button click

                                                Toast.makeText(getApplicationContext(), "Second Button Action",

                                                                        Toast.LENGTH_SHORT).show();

 

                                    }

                        });

            }

 

            @Override

            public boolean onCreateOptionsMenu(Menu menu) {

                        // Inflate the menu; this adds items to the action bar if it is present.

                        getMenuInflater().inflate(R.menu.main, menu);

                        return true;

            }

 

4.      Now create a class for create vertical button

package com.example.customviewexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
             Button btnFirst, btnSecond;

             @Override
             protected void onCreate(Bundle savedInstanceState) {
                         super.onCreate(savedInstanceState);
                         setContentView(R.layout.activity_main);
                         btnFirst = (Button) findViewById(R.id.firstButton);
                         btnSecond = (Button) findViewById(R.id.secondButton);
                         btnFirst.setOnClickListener(new OnClickListener() { 

                                     @Override
                                     public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                 // Show toast message on First button click
                                                 Toast.makeText(getApplicationContext(), "First Button Action",
                                                                         Toast.LENGTH_SHORT).show(); 

                                     }

                         });
                         btnSecond.setOnClickListener(new OnClickListener() {

                                     @Override
                                     public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                 // Show toast message on Second button click
                                                 Toast.makeText(getApplicationContext(), "Second Button Action",
                                                                         Toast.LENGTH_SHORT).show();

                                     }

                         });

            }
             @Override
             public boolean onCreateOptionsMenu(Menu menu) {
                        // Inflate the menu; this adds items to the action bar if it is present.
                         getMenuInflater().inflate(R.menu.main, menu);
                         return true;

            }

 }

 

5.      Create another class for create rounded image

 

package com.example.customviewexample; 

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.Bitmap.Config;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.PorterDuff.Mode;

import android.graphics.PorterDuffXfermode;

import android.graphics.Rect;

import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.Drawable;

import android.util.AttributeSet;

import android.widget.ImageView;

 

// This class make your Image Rounded

public class RoundedImageView extends ImageView {

 

            public RoundedImageView(Context ctx, AttributeSet attrs) {

                        super(ctx, attrs);

            }

 

            @Override

            protected void onDraw(Canvas canvas) {

                         Drawable drawable = getDrawable(); 

                        if (drawable == null) {

                                    return;

                        }

 

                        if (getWidth() == 0 || getHeight() == 0) {

                                    return;

                        }

                        // A Bitmap to hold the pixels,

                        Bitmap b = ((BitmapDrawable) drawable).getBitmap();

                        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

 

                        int w = getWidth(), h = getHeight();

 

                        Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);

                        canvas.drawBitmap(roundBitmap, 0, 0, null);

 

            } 

            // Round and crop your image

            public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) { 

                        Bitmap finalBitmap;

                        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)

                                    finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,

                                                            false);

                        else

                                    finalBitmap = bitmap;

                        // Basically your problem arises form the fact that you create a bitmap.

                        // You don't put anything in it. You then create a smaller bitmap and

                        // then you render an imageView to that smaller bitmap.

                        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),

                                                finalBitmap.getHeight(), Config.ARGB_8888);

                        // a Canvas to host the draw calls (writing into the bitmap)

                        Canvas canvas = new Canvas(output);

                        // The Paint class holds the style and color information about how to

                        // draw geometries, text and bitmaps.

                        final Paint paint = new Paint();

                        // Rect holds four integer coordinates for a rectangle

                        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),

                                                finalBitmap.getHeight());

 

                        paint.setAntiAlias(true);

                        paint.setFilterBitmap(true);

                        paint.setDither(true);

                        canvas.drawARGB(0, 0, 0, 0);

                        paint.setColor(Color.parseColor("#BAB399"));

                        // draw circle with radius

                        canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,

                                                finalBitmap.getHeight() / 2 + 0.7f,

                                                finalBitmap.getWidth() / 2 + 0.1f, paint);

                        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

                        canvas.drawBitmap(finalBitmap, rect, rect, paint);

 

                        return output;

            }

 

}

6.      Now create control in 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="horizontal"

    tools:context=".MainActivity" >

 

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="fill_parent"

        android:orientation="vertical" >

 

        <!-- your PackageName.Customclass -->

       

        <!-- <Button -->

        <com.example.customviewexample.CustomView

            android:id="@+id/firstButton"

            android:layout_width="wrap_content"

            android:layout_height="0dp"

            android:layout_weight=".50"

            android:text="First" />

       

        <!-- <Button -->

        <com.example.customviewexample.CustomView

            android:id="@+id/secondButton"

            android:layout_width="wrap_content"

            android:layout_height="0dp"

            android:layout_marginTop="-8sp"

            android:layout_weight=".50"

            android:text="Second" />

    </LinearLayout>

 

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content" >

 

        <!-- <ImageView -->

        <com.example.customviewexample.RoundedImageView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginLeft="70sp"

            android:src="@drawable/chrome" />

    </LinearLayout>

 

</LinearLayout> 

7.      Now run your application

Without use custom view my activity will look like this:


Creating custom and compound Views in Android

Whereas, after using Custom view Activity, UI will look like:


Creating custom and compound Views in Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By