我有一個按鈕的自定義視圖類,我讓用戶觸摸屏幕,所以我可以檢索座標。我想要做的是,每當他點擊按鈕時,將其文本設置爲他的觸摸座標。我該怎麼做呢?同一類中的訪問變量
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;
}
.
.
.
}
編輯 我添加了一個Log.d按鈕監聽器裏,似乎該按鈕被點擊的用戶觸摸屏幕和變化X的休息,Y(文字更改爲「僅前0.0" )。
我的.xml文件:
<?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>
座標通常在onTouchEvent內部返回,但我注意到一些奇怪的東西。觸摸視圖後,按鈕偵聽器似乎停止偵聽,並且x和y發生更改。 –