<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"> <EditText android:id="@+id/txt_1" android:layout_width="200dp" android:layout_height="wrap_content"/> <Button android:id="@+id/but_1" android:text="确认" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <com.android.canvstest.TestView android:layout_height="wrap_content" android:id="@+id/textview1" android:layout_width="wrap_content"/> </LinearLayout>
package com.android.canvstest; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import androidx.annotation.Nullable; public class TestView extends View { int x,y; public TestView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } void setXY(int x1,int y1){ x=x1; y=y1; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.BLUE); Paint paint=new Paint(); paint.setAntiAlias(true); paint.setColor(Color.GREEN); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(x,y,50,paint); paint.setColor(Color.RED); canvas.drawCircle(x,y,10,paint); paint.setColor(Color.WHITE); canvas.drawRect(800,800,1000,1000,paint); } }
package com.android.canvstest; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TestView testView = findViewById(R.id.textview1); Button button = findViewById(R.id.but_1); final EditText editText = findViewById(R.id.txt_1); testView.setXY(100, 100); testView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int x,y; x = (int) event.getX(); y = (int) event.getY(); if (event.getAction() == MotionEvent.ACTION_DOWN){ testView.setXY(x,y); testView.invalidate(); } else if (event.getAction() == MotionEvent.ACTION_MOVE){ testView.setXY(x,y); testView.invalidate(); } else if (event.getAction() == MotionEvent.ACTION_UP){ x = (int) event.getX(); y = (int) event.getY(); Log.d("1", String.valueOf(x)); if(x>=850&&x<=950&&y>=850&&y<=950){ System.exit(0); } } return true; } }); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int x=100; x = Integer.parseInt(editText.getText().toString()); testView.setXY(x,100); testView.invalidate(); } }); } }