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。

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了