我在一個活動中有一個ImageView,其左上角座標必須檢索,因此我可以將圖像視圖分成5個觸摸區域。我使用getLocationOnScreen獲取這些座標。Android中ImageView的左上角座標顯示不正確
X座標很好,但Y座標由於某種原因似乎有缺陷,總是有一個偏移量,它似乎指向窗口的頂部(通過啓用指針接觸開發工具進行驗證)。
下面是活動代碼:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
amslerView = (ImageView) findViewById(R.id.amsler_grid);
locText = (TextView) findViewById(R.id.locationLabel);
amslerView.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN :
startX = (int) event.getRawX();
startY = (int) event.getRawY();
int[] loc = new int[2];
amslerView.getLocationOnScreen(loc);
Log.i("Screen Location of View", "X:" + loc[0] + "\t Y:" + loc[1]);
locText.setText("Location " + startX + " " + startY + "Screen View Location is " + "X:" + loc[0] + "\t Y:" + loc[1]);
break;
case MotionEvent.ACTION_UP :
endX = (int) event.getX();
endY = (int) event.getY();
// locText.setText("End Location " + endX + "\t" +
// endY);
break;
}
return true;
}
});
}
下面是XML佈局:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/amsler_grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:adjustViewBounds="true"
android:contentDescription="Amsler Grid"
android:padding="0dp"
android:scaleType="center"
android:src="@drawable/amsler_boundary" />
這是我面臨的問題的截圖:http://puu.sh/4d1LJ.jpg
正如你可以看到,X座標很好,但Y座標顯示的位置是http://puu.sh/4d1OJ.jpg
任何幫助表示讚賞,我坦率地在一個損失爲什麼發生這種情況。
這是我使用getX()時得到的結果。我已經嘗試了幾乎所有代碼組合來嘗試獲取座標,但到目前爲止總是存在Y的偏移量。 –
Hav3n