这是我自定义View 的源码:
public class MyView extends View {
private float px;
private float py;
private int flag ;
private Bitmap map;
public MyView(Context context,float p_x,float p_y,int flag) {
super(context);
this.px=p_x;
this.py=p_y;
this.flag=flag;
System.out.println(px);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
System.out.println("2");
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(flag==1){
map=BitmapFactory.decodeResource(getResources(), R.drawable.star_circle_mo);
}
else{
map=BitmapFactory.decodeResource(getResources(), R.drawable.star_circle_mo1);
}
System.out.println("p_x"+px);
System.out.println("p_y"+py);
canvas.drawBitmap(map, 45.0f, 180.0f, null);
}
}
在这里面调用它:
public class PicBuyDemo extends Activity {
private ImageView iv;
private MyView myView;
private MyView ball;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
iv=(ImageView)findViewById(R.id.iv);
ball=(MyView)findViewById(R.id.myView_01);
iv.setBackgroundResource(R.drawable.j1);
myView =new MyView(this,80.0f,70.0f,1);
iv.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
ball.setVisibility(View.VISIBLE);
return false;
}
});
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/ll"
>
<ImageView android:id="@+id/iv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<com.cyc.MyView
android:id="@+id/myView_01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
>
</com.cyc.MyView>
为什么在自定义View的ondraw()方法里px,py总是为0.0,flag=0