I followed the thread answered by Gautier Haroun on how to create a touchscreen and allow tapping and displaying the coordinate. But I want to normalize the coordinate by dividing with the text view width and height respectively to get a range between 0~1.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView textView = (TextView)findViewById(R.id.textView);
// this is the view on which you will listen for touch events
final View touchView = findViewById(R.id.touchView);
final float touchWidth = touchView.getWidth();
final float touchHeight = touchView.getHeight();
touchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()/touchWidth) + " x " + String.valueOf(event.getY()/touchHeight));
return true;
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
Then the layout:
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, TestActivity"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="@+id/touchView"
android:background="#f00"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:alpha="0.5" />
I tried final float touchWidth = touchView.getWidth();
But the result is infinite, so touch Width is 0 instead of around 1500 in my case. Can you tell me how to get the width and height of the View object touch View?
Thanks