I have a custom view class with a button and I let the user touch the screen so I can retrieve the coordinates. What I want to do is, whenever he clicks the button, to set its text to the coordinates of his touch. How do I do this?
public class TargetView extends RelativeLayout{ . . . public float x=0; public float y=0; public TargetView(final Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); ((Activity)getContext()) .getLayoutInflater() .inflate(R.layout.target_view, this, true); Target=findViewById(R.id.target); Undo=(Button)findViewById(R.id.undo_bt); Undo.setOnClickListener(new OnClickListener(){ public void onClick(View v) { Log.d("x,y",(String.valueOf(x)+","+String.valueOf(y))); Undo.setText(String.valueOf(x)+","+String.valueOf(y)); } }); @Override public boolean onTouchEvent(MotionEvent event){ switch (event.getAction()){ case (MotionEvent.ACTION_DOWN): { x = event.getX(); y = event.getY(); } return false; } . . . } EDIT I have added a Log.d inside the button listener and it seems that the button gets clicked only before the user touches the rest of the screen and changes x,y (text changes to "0.0").
My .xml files:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <android.archer.test.TargetView android:id="@+id/myTargetView" android:layout_width="300dip" android:layout_height="300dip" android:layout_gravity="center_horizontal" android:background="@drawable/target" > </android.archer.test.TargetView> </LinearLayout> <merge xmlns:android="http://schemas.android.com/apk/res/android"> <View android:id="@+id/target" android:layout_width="300dp" android:layout_height="350dip" /> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/undo_bt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:text="-" /> </RelativeLayout>