qq6513568061
2011-01-11 11:15
浏览 287

Android 自定义View 参数

这是我自定义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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongya1987 2011-01-11 14:25
    已采纳

    myView =new MyView(this,80.0f,70.0f,1); (1)
    这一行根本没有任何用处
    ball=(MyView)findViewById(R.id.myView_01); (2)
    这句话是从xml读出MyView,调用的构造方法是
    public MyView(Context context, AttributeSet attrs)
    你在代码(1)中创建的这个myView根本就没有加入到布局中,也自然没有执行它的onDraw。

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题