How To Draw Using An Xml Layout In Android
I am trying to work through an android example given on the developers' page. It gives 2 ways of drawing on a canvas. The first way is to use a class called CustomDrawableView, whi
Solution 1:
If the tutorial is correct then the only change you make is to add that constructor. You probably want to move the drawable init code to a separate method.
public CustomDrawableView(Context context, AttributeSet attrs) {
super(context, attrs);
initDrawable();
}
The xml
<com.example.shapedrawable.CustomDrawableView
android:id="+id/custom_drawable_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
And you can obtain the view like this.
CustomDrawableView mCustomDrawableView;
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // assuming your layout is named main.xml
mCustomDrawableView = (CustomDrawableView) findViewById(R.id.custom_drawable_view);
}
Solution 2:
public CustomDrawableView(Context v,AttributeSet as){ super(v,as); drawShape(as); } public void drawShape(AttributeSet ast) { int x =0; int y=0 ; int width=0; int height=0 ;
x=Integer.parseInt(ast.getAttributeValue(null, "x"));
y=Integer.parseInt(ast.getAttributeValue(null, "y"));
width=Integer.parseInt(ast.getAttributeValue(null, "width"));
height= Integer.parseInt(ast.getAttributeValue(null, "height"));
mDrawable = newShapeDrawable(newOvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
} }
MainActivity.java{ CustomDrawableView mCustomDrawableView;
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
publicView.OnClickListener cc = (newView.OnClickListener() {
publicvoidonClick(View view) {
setContentView(R.id.myid);}
});
} This works fine..(Not so sure whether this is the best way to do it...)
Post a Comment for "How To Draw Using An Xml Layout In Android"