[英]How to work with the X,Y Coordinates in android
我是Android的新手,我正在尝试使用触摸屏将图形定位在正确的坐标处。 当我触摸屏幕时,我获得了坐标(x,y),但是当我按下按钮绘制圆时,它将在我触摸的点以下的位置绘制圆。我使用relativeLyout作为布局,我给了它一个ID为“布局”,我曾在我的java类中引用它。我认为这是因为我正在使用addView绘制相同的布局。我尽了最大的努力来纠正它,但没有。 (按一下按钮后便拉出了圆环,但位置并不在我想要的位置,它位于我所触摸的位置下方)有人可以帮助我。 这是我的代码。
public class MyView extends View{
float x ;
float y ;
int radius = 20;
public MyView(Context context, float x, float y){
super(context);
this.x = x;
this.y = y;
} //end constructor
public void onDraw(Canvas canvas){
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
canvas.drawCircle(x, y, radius, paint);
} //end onDraw
} //end class MyView
这是我的主要课程:
public class ButtonClickActivity extends Activity implements OnClickListener{
RelativeLayout laying;
Button button;
MyView myView;
private static float x=100;
private static float y=100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_click);
laying = (RelativeLayout) findViewById(R.id.layout);
button = (Button) findViewById(R.id.circle);
//set listeners
button.setOnClickListener(this);
} //end onCreate
public void onClick(View view){
switch(view.getId()){
case R.id.circle:
myView = new MyView(this, x, y);
laying.addView(myView);}
这是触控事件
public boolean onTouchEvent(MotionEvent event){
int action = event.getAction();
//get the type of action
switch(action){
case MotionEvent.ACTION_DOWN: //you have touch the screen
x = event.getX();
y = event.getY();
break
}
}
这是布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:id="@+id/layout" >
<Button
android:id="@+id/circle"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight = "1"
android:text="Circle"/>
</RelativeLayout>
您错过的是视图的大小。 您的自定义视图不知道圆需要多少空间,默认视图是包装内容,那么最小尺寸是多少? 正确:0。
这就是为什么您看不到任何东西的原因。 您可以从视图外部设置尺寸,也可以在视图内部以某种方式自己测量尺寸,然后告诉父视图该视图所需的尺寸(然后检查父级为您提供的尺寸并使用它)。
在此处阅读有关自定义视图的更多信息。
顺便说一句,不建议在onDraw内部创建绘画,至少不以每次调用时都重新创建它的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.