geshegentle
TTTjun
2015-11-05 09:24

Android 自定义View点击事件

  • canvas

给自定义小图标(箭头所指)添加OnclickListener();

结果

只要点击屏幕就会响应了

刚接触Android不久,不知道哪里的问题,求大神指点。

图片说明

public class Map extends Fragment implements OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View root = inflater.inflate(R.layout.map, container, false);
        FrameLayout frameLayout = (FrameLayout) root
                .findViewById(R.id.maplayout);
        /**
         * 新建一个图标
         * 
         * @author prohan
         * @param Context
         *            context int x ,int y 添加的点的左上角位置 int id 设置节点ID
         */
        final Myview myview = new Myview(this.getActivity(), 830, 880);
        myview.setOnClickListener(this);
        myview.setId(10);
        frameLayout.addView(myview);
        return root;
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    class Myview extends View {
        public int bitmapx;
        public int bitmapy;

        public Myview(Context context, int x, int y) {
            super(context);
            this.bitmapx = x;
            this.bitmapy = y;

        }

        @Override
        protected void onDraw(Canvas canvas) {

            Paint point = new Paint();
            point.setAlpha(150);

            Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
                    R.drawable.point);
            canvas.drawBitmap(bitmap, null, new Rect(bitmapx, bitmapy,
                    bitmapx + 60, bitmapy + 100), point);
            // canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
            // canvas.drawBitmap(bitmap, bitmapx, bitmapy, point);

        }

    }

    // Onclick中的方法
    private void alertmessage() {
        AlertDialog alert = new AlertDialog.Builder(this.getActivity())
                .create();
        alert.setIcon(R.drawable.ic_launcher);// 设置对话框的图标
        alert.setTitle("当前站点信息:");
        alert.setMessage("XXXXXXXXXXXXXXXX");
        alert.show();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case 10:
            Toast.makeText(getActivity(), "#" + v.getId() + "#" + "8号楼监测站",
                    Toast.LENGTH_SHORT).show();
            alertmessage();
            break;

        default:
            break;
        }

    }
}

如果能告诉我如何能让myview跳动起来就最好啦

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换