代码之家  ›  专栏  ›  技术社区  ›  MyName

如何创建一个有形状的可点击按钮?

  •  1
  • MyName  · 技术社区  · 15 年前

    我试图在画布上绘制一个形状,并获取有关用户在该画布上执行的单击的信息。

    我创建了一个扩展Button类的类。

      class CustomDrawableButton extends Button {
        private final ShapeDrawable mDrawable;
        int x = 50;
        int y = 50;
        int width = 30;
        int height = 30;
    
        public CustomDrawableButton (Context context) {
           super(context);
           mDrawable = new ShapeDrawable (new OvalShape ());
           mDrawable.getPaint().setColor(Color.GREEN);
           mDrawable.setBounds(x, y, x + width, y + height);
        }
    
        protected void onDraw(Canvas canvas) {
          mDrawable.draw(canvas);
        }
      }
    

    然后,在一个扩展了View的类中,我添加了实例化和侦听器:

      CustomDrawableButton mCustomDrawableButton = new CustomDrawableButton(getBaseContext());
    
      layout.addView(mCustomDrawableButton);
    
      mCustomDrawableButton.draw(canvas);
    
      mCustomDrawableButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
          System.out.println("Yey clicked");
         Toast.makeText(view.getContext(), "Yey", Toast.LENGTH_LONG).show();
        }});
    

    这可能吗?如果不是这样的话,你能告诉我一些方法来获取有关在画布或视图上按下的屏幕坐标的信息吗?

    1 回复  |  直到 12 年前
        1
  •  0
  •   MyName    15 年前

    经过一段时间的搜索,这里有一个教程,说明如何使用触摸屏的位置。

    http://marakana.com/tutorials/android/2d-graphics-example.html

    仍然不知道如何通过自动将触摸到的事件绑定到按钮来实现。如果有人知道怎么做,请说出来。