Breaking News
Loading...
Tuesday, 10 December 2013

Include custom view in XML

08:07
The exercise show how to refer custom view in XML.

Include custom view in XML


Create custom view extending View in separated file, MyView.java.
package com.example.androidpaint;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

Bitmap myBitmap;
int minWidth, minHeight;

public MyView(Context context) {
super(context);
init();
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

private void init(){
myBitmap = BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher);
minWidth = myBitmap.getWidth();
minHeight = myBitmap.getHeight();
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(myBitmap, 0, 0, null);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(minWidth, minHeight);
}

}


Include <com.example.androidpaint.MyView> in layout XML. where com.example.androidpaint is our package.
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"/>

<com.example.androidpaint.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.example.androidpaint.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="another button"/>

</LinearLayout>


0 comments:

Post a Comment

 
Toggle Footer