qq6513568061 2011-01-11 11:15
浏览 291
已采纳

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。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)