Android- Draw line between two views

妖精的绣舞 提交于 2019-12-30 13:54:28

问题


Below is my program where I have created three new views in a frame. On click of two different views I want to draw a line between the views. I am trying to figure out how to do this...

    Ball ball1=new Ball(this,100,100,45);
    Ball ball2=new Ball(this,400,100,45);
    Ball ball3=new Ball(this,250,350,45);
    FrameLayout frame1=(FrameLayout) findViewById(R.id.main_view);
    frame1.addView(ball1);
    frame1.addView(ball2);
    frame1.addView(ball3);

      frame1.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()){
            case MotionEvent.ACTION_DOWN: {
                float x = event.getX();
                float y = event.getY();
                System.out.println("x:"+x+"y:"+y);
                if (x>55 && x<142 && y>55 && y<142) 
                    {
                    System.out.println("working1 "+count);
                    Toast toast = Toast.makeText(getBaseContext(), "Works fine", Toast.LENGTH_SHORT);
                    toast.show();
                }

回答1:


For a draw line between your two views.

Create class for view which draw a line.

public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);
        paint.setColor(Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
            canvas.drawLine(0, 50, 350, 50, paint);
    }

}

now from your activtiy where you want to add this line in your layout. Create object of this class and add this view in your layout.

According to your requirment try like this.

DrawView drawView; drawView = new DrawView(this);

frame1.addView(ball1);
                            // add that view here
frame1.addView(drawView);
frame1.addView(ball2);
                            // same way here
frame1.addView(ball3);

For more Detail See Example




回答2:


Just draw line in onDraw() on some condition and set this condition in your activity in onTouch() method. Then call invalidate on Views that you changed their condition.



来源:https://stackoverflow.com/questions/13616223/android-draw-line-between-two-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!