Wednesday, July 17, 2013

Android: custom View with draw + xml layout

create custom View class:
public class MyCanvas extends View {
int x = 0;
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

Paint paint = new Paint();
Rect rect = new Rect();
protected void onDraw(Canvas canvas){
paint.setColor(0xFF999999);
rect.set(x, 100, 200, 150);
canvas.drawRect(rect, paint);
}
public void move(){
x+=5;
this.invalidate(); // redraw
}
}

xml layout:
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" android:id="@+id/layout1">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="21dp"
        android:text="Button" />

    <com.boon.MyCanvas
        android:id="@+id/myCanvas1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:background="#CCCCCC" />

</RelativeLayout>

MainActivity.java: 
public class MainActivity extends Activity implements View.OnClickListener{
Button b;
MyCanvas c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)this.findViewById(R.id.button1);
b.setOnClickListener(this);
c = (MyCanvas) this.findViewById(R.id.myCanvas1);
}

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

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
c.move();
}

}

No comments: