Saturday 22 February 2014

Creating Custom Views in Android: User Defined Views

So you are accustomed to created views using the layout XML files in Android. Let us see how you can more efficiently control the user interface creating your own custom view. This tutorial expects that you have set up Android in your system and that you can run apps that you write in simulator, or even better, on a real device.

Create a new Android application using Eclipse. Modify your activity java class (MainActivity) and add a new java class(MyView). Here is a sample of your source files:

<MainActivity.java>

package com.first;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView view =new MyView(this);
        setContentView(view);
    }


    @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;
    }
   
}

<MyView.java>

package com.first;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.widget.ImageView;

public class MyView extends ImageView {

    private Paint paint;
    private int width;
    private int height;

    public MyView(Context context) {
        super(context);
        paint = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //hello world
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        paint.setTextSize(16);
        paint.setColor(Color.BLACK);
        paint.setTextAlign(Align.CENTER);
        String text = "Hello there!";
        canvas.drawText(text, width / 2, height/2, paint);

        // footer
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        paint.setTextSize(12);
        paint.setColor(Color.BLUE);
        paint.setTextAlign(Align.CENTER);
        String footer = "© Varun Nair.";
        canvas.drawText(footer, width / 2, height - 25, paint);
    }

    @Override
    public void onSizeChanged(int w, int h, int oldW, int oldH) {
        height = h;
        width = w;
    }
}

No comments:

Post a Comment