Draw editview / textview on fingertouch in Android - android

I am newbie in Android, in my app I required draw textview/editview on finger touch where user is able to type in that.I searched a lot but find nothing relevant.
I found links to draw editview/text but not on fingertouch.

You can accomplish this by registering touch events on a view. And when the touch event fires, you can then create a EditText/TextView based on the touch event coordinates.
class YourMainClass extends Activity{
public void onCreate(Bundle bundle)
{
//Do your normal UI initialization here
your_layout.setOnTouchListener(new TouchListener()); //where your_layout is the layout/view of your Activity that should register the touch events.
}
class TouchListener implements OnTouchListener
{
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); //See note below
params.leftMargin = (int)event.getX() - v.getLeft();
params.topMargin = (int)event.getY() - v.getTop();
EditText edit = new EditText(this);
edit.setLayoutParams(params);
your_layout.addView(edit);
return true;
}
}
}
}
Note: Be sure to change the LayoutParams type to the type of layout you use (for example: LinearLayout.LayoutParams if you're using a LinearLayout to place the EditText in).
Also if you use padding, the coordinates of the actual EditText might be off (since the padding area is still counted as the View when using v.getLeft() and v.getTop(), but not when adding the EditText to your layout).

Related

How to detect touch when you are moving over a button

I have created a button at the center of the layout with width 50dp.If I touch the screen at left extreme side of the layout(where the is no button) and hold down (Keep pressing ) till I reach the button in center then it should detect the touch .How can I do that .I have tried both onCLicklistener() and onTouchListener() but I still cannot detect the touch .
Basically like gesture but I thought button had a way of detecting that.
button.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// Toast text : entered within button
return false;
}
}))
If we set Click or Touch listener to Button which is 50dp width at center, then the listener will get callback only if the user click/touch initiating from button.
While in your problem case, You are initiating click/touch from outside and coming to button.
So, button listener will not get callback from Android Framework
For your requirement to work, we need to add some logic, i have tried to add it here :
activity_main.xml :
<RelativeLayout android:id="#+id/parentLayout" ... >
<Button android:id="#+id/buttonCenter ... />
</RelativeLayout>
MainActivity.java :
// apply touch listener to parentLayout
button = (Button) findViewById(R.id.buttonCenter);
parent = (RelativeLayout) findViewById(R.id.parentLayout);
parent.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("tag","in onTouch...");
checkTouch(event);
return true;
}
});
// check if touch entered button area
// save button left, right, top and bottom edge
// update : This is API i found on google documentation
float[] params;
button.getLocationOnScreen(params);
public void checkTouch(MotionEvent event) {
x = event.getX();
y = event.getY();
if(x >= param[0] && x <= (param[0]+button.getWidth())) {
if(y >= param[1] && y <= (param[1]+button.getHeight())) {
Log.d("tag","this touch is in button area");
// do what you want to do when touch/click comes in button area
}
}
}
Actually when you place a touch MotionEvent.ACTION_DOWN event is dispatched on the view which you touch and as you move MotionEvent.ACTION_MOVE events will be dispatched for every pixel point moved and until you release viz. until MotionEvent.ACTION_UP event is dispatched on that same view the events will not be handed over to any other view.
That is why it is not detecting on the button since it is actually the event of its parent view. So write an ontouchlistener on the parent and in that handle the touch according to the event.getRawX() & event.getRawY() positions in pixels.

Add Image to layout on touch in android with respect to touch position

Where ever i touch on the screen with respect to x y position i need to add one image on that particular position.
I tried by implementing the ontouch listener but it is adding image to different position and many images are being appeared on many touch i want some thing like where ever i touch that same image should appear there
Please Help i am new to android working on project in a compnay
This is my activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.wwcontainer);
//Set On TouchListner to the Layout
rl.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("OnTouch", "On Touch View Group....");
int x = (int) event.getX();
int y = (int) event.getY();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.icon);
imageView.setLayoutParams(new LayoutParams(x,y));
rl.addView(imageView);
return true;
}
});
}
I know about drag and drop i dont want drag and drop instead i need touch any where there image should appear wrt touch position please help me
I had same request and this is what i done and it worked perfectly for me
final RelativeLayout rr = (RelativeLayout) findViewById(R.id.rr);
rr.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView iv = new ImageView(getApplicationContext());
lp.setMargins(x, y, 0, 0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(
R.drawable.gr1));
((ViewGroup) v).addView(iv);
}
return false;
}
});
This will place image to RelativeLayout where you touched starting coordinates from there. If you want to center new image where you touched RelativeLayout you need to calculate Height and Width of your image and change one line in my code to
lp.setMargins(x - yourImageWidth/2, y - yourImageHeight/2, 0, 0);
You need to use AbsoluteLayout instead of RelativeLayout.
To add image at particular x,y location, you need AbsoluteLayout.
Did you check what int value getX() and getY() returns i think it will return 0,0.
please use event.getRawX() & event.getRawX() for actual touch position. i hope it will help.

OnClickListener on scrollView

I have a scrollView with lot of elements
ScrollView scroller = (ScrollView)findViewById(R.id.scrollView);
I need to attach an onClickListener to the scrollview so I do
scroller.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// This is all you need to do to 3D flip
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
But this is not getting triggered when I touch. Any Ideas?
The best solution seem to put LinearLayout into ScrollView and set the setOnClickListener on it.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myLayout"
android:clickable="true"
android:orientation="vertical">
<!-- content here -->
</LinearLayout>
</ScrollView>
in the Activity :
LinearLayout lin = (LinearLayout) fragment.rootView.findViewById(R.id.myLayout);
lin.setOnTouchListener(new setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Whatever
}
});
You need to set the setOnClickListener directly on the ScrollView's child.
Since a ScrollView can have only one child, you can simply use this approach:
ScrollView scrollView = //...
View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
// ...
}
//Set the onClickListener directly on the ScrollView's child
scrollView.getChildAt(0).setOnClickListener(mOnClickListener);
It is because the child of the ScrollView is getting the touch event of the user and not the ScrollView. You must set android:clickable="false" attribute to each and every child of the ScrollView for the onClickListener to work on ScrollView.
Or else the alternate could be to set the onClickListener on each of the ScrollView's children and handle it.
UPDATE 22/12/2020
sadly this also triggers after each scroll event.
This the actually the answer to the question without any odd cases by using View.OnTouchListener instead of View.OnClickListener on the ScrollView and detecting the MotionEvent.ACTION_UP where the finger is left off the screen.
To make sure that it's not a scroll, then save previous touched screen x, y values of the MotionEvent.ACTION_DOWN and compare it to those of MotionEvent.ACTION_UP. If they are not equal then certainly the user is moving their finger (i.e. scrolling) before they left it off the screen.
int mXOld, mYOld; // field values to save the tap down on the ScrollView
scrollView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mXOld = x;
mYOld = y;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (x == mXOld || y == mYOld) { // detecting it's not a horizontal/vertical scrolling in ScrollView
// HERE add the code you need when the ScrollView is clicked
Toast.makeText(MainActivity.this, "Click", Toast.LENGTH_SHORT).show();
return false;
}
}
return false;
}
});
Original Answer: Odd case that is different than the question
My problem was somehow different, so I wanted to share it..
I have a ScrollView that I have to use match_parent in its width & height; and I have an internal TextView that is centered in the ScrollView.
The text of the TextView can be long so it occupies the full height of the ScrollView, and sometimes it can be short, so there will be blank areas on the top and bottom., So setting the OnClickListener on the TextView didn't help me whenever the text is short as I want the blank areas detects the click event as well; and also the OnClickListener on the ScrollView doesn't work..
So, I solved this by setting OnTouchListener on the ScrollView and put code into MotionEvent.ACTION_UP So it can kind of simulating complete tap by lefting off the finger off the screen.
private View.OnTouchListener mScrollViewTouchListener = new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// DO Something HERE...
}
return false;
}
};
As #Zain pointed out, sometimes it is necessary to capture OnClicks for the whole area of the Scrollview, while the childs may be smaller or invisible.
To circumvent scrolling detected as an onClick, we used a GestureDetector:
final protected GestureDetector gestureDetector = new GestureDetector(getActivity(),
new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
in onCreateView
scrollView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(gestureDetector.onTouchEvent(event)){
[do stuff]
}
return false;
}
});
I think you can custom a ScrollView, override the dispatchTouchEvent method, add add the custom onClick callback.

Android (x,y) continuous touch (drag) coordinates

I'm new to android, and I've been trying for a while to find out how can I retrieve the coordinates of a continuous touch on the screen. for example have 2 vars (x,y) that update in real time as finger moves around. I got it how to find it when the touch is made, but I really don;t get it how to make it return the result after that , when the finger is moving.
I've been trying switch statements, while/for loops in different combination with ACTION_MOVE./ UP/ DOWN .. .still nothing.
I've found like the same question on the website, but the answers only fit for the first step(showing the coordination from the touch only)
I'd really appreciate a solution to this! Thanks!
Without seeing your code I'm just guessing, but essentially if you don't return true to the first call to onTouchEvent, you won't see any of the subsequent events in the gesture (MOVE, UP, etc).
Maybe that is your problem? Otherwise please put code sample up.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView xCoord = (TextView) findViewById(R.id.textView1);
final TextView yCoord = (TextView) findViewById(R.id.textView2);
final View touchView = findViewById(R.id.textView3);
touchView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
xCoord.setText(String.valueOf((int) event.getX()));
yCoord.setText(String.valueOf((int) event.getY()));
break;
}
case MotionEvent.ACTION_MOVE:{
xCoord.setText(String.valueOf((int) event.getX()));
yCoord.setText(String.valueOf((int) event.getY()));
break;
}
}
return true;
}
});
}
You need to implement an OnTouchListener for whatever view you want to recognize the drag.
Then in the OnTouchListener you need to display the X and Y coordinates. I believe you can get those via MotionEvent.getRawX() and MotionEvent.getRawY()
You can use the MotionEvent.getAction() method to find out when a drag is occurring. I believe the constant is MotionEvent.ACTION_MOVE. Here is some psuedo-code:
Add OnTouchListener interface
public class XYZ extends Activity implements OnTouchListener
Register the listener in the onCreate method
public void onCreate(Bundle savedInstanceState)
{
//other code
View onTouchView = findViewById(R.id.whatever_id);
onTouchView.setOnTouchListener(this);
}
Implement the onTouch method
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_MOVE)
{
float x = event.getRawX();
float y = event.getRawY();
// Code to display x and y go here
// you can print the x and y coordinate in a textView for exemple
}
}

Detect which view your finger is sliding over in Android

While similar questions have been asked in the past they don't seem to really have been answered which might be due to confusion as to what's being asked.
Put simply, I'd like to detect which view is being entered as your finger slides over the screen. The best example of this in action is the soft keyboard on any android phone. When you press any key it shows up as a popup to tell you what letter is under your finger. If you now move your finger over the keyboard in a single gesture the various letters pop up as you move over the various letters of the alphabet.
What listeners are used for this type of behaviour. I've tried OnTouchListeners but they seem to be only when you 'touch' the button as opposed to 'finger past' them
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {doStuff();}
});
button.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
doStuff();
return false;
}
});
OnFocusChangeListener don't help either.
create a Layout
add Views to your Layout
set the setOnTouchListener to your Layout
override the onTouch method with the following:
public boolean onTouch(View v, MotionEvent event)
{
LinearLayout layout = (LinearLayout)v;
for(int i =0; i< layout.getChildCount(); i++)
{
View view = layout.getChildAt(i);
Rect outRect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
if(outRect.contains((int)event.getX(), (int)event.getY()))
{
// over a View
}
}
}
EDIT:
I saw keyboard. I guess, it just one view and coordinates of every letter is known. So you can easily compute which letter the user slides through
AND NOW THE ANSWER:
I'm not sure, but probably this code helps your.
It's so far away, I wrote it for me. But the idea is following.
If I remember right, there is no gesturedetector for views, but you can combine touchlistener of the view with geturelistener of your activity.
Once you've touched your view, you have
private GestureDetector mGestureDetector;
// x and y coordinates within our view
private static float sideIndexX;
private static float sideIndexY;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
mGestureDetector = new GestureDetector(this, new SideIndexGestureListener());
}
class MyGestureListener extends
GestureDetector.SimpleOnGestureListener
{
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY)
{
// we know already coordinates of first touch
// we know as well a scroll distance
sideIndexX = sideIndexX - distanceX;
sideIndexY = sideIndexY - distanceY;
// when the user scrolls within our side index
// we can show for every position in it a proper
// item in the country list
if (sideIndexX >= 0 && sideIndexY >= 0)
{
doStuff();
}
return super.onScroll(e1, e2, distanceX, distanceY);
}
}
button.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
// now you know coordinates of touch
// store them
sideIndexX = event.getX();
sideIndexY = event.getY();
doStuff();
return false;
}
});
You may want to try GestureDetector.
http://android-developers.blogspot.com/2010/06/making-sense-of-multitouch.html
it's geared to multitouch, but this is a good start toward understanding android touch/gestures, next stop, api docs/samples
The simple answer is you can't - not like the iPhone when in accessibility mode.
Until Ice Cream Sandwich that is. It now has the iPhone-like capability of being able to identify elements under your finger without having to lift it.
It's fairly straight forward to handle this manually.
Using your parent layout as the onTouchListener (in the following example, I extend a RelativeLayout), you can check for collisions between a MotionEvent and the child Views using simple co-ordinate comparison logic:
/** Returns the View colliding with the TouchEvent. */
private final View getCollisionWith(final MotionEvent pMotionEvent) {
// Declare the LocationBuffer.
final int[] lLocationBuffer = new int[2];
// Iterate the children.
for(int i = 0; i < this.getChildCount(); i++) { /** TODO: Order. */
// Fetch the child View.
final View lView = this.getChildAt(i);
// Fetch the View's location.
lView.getLocationOnScreen(lLocationBuffer);
// Is the View colliding?
if(pMotionEvent.getRawX() > lLocationBuffer[0] && pMotionEvent.getRawX() < lLocationBuffer[0] + lView.getWidth() && pMotionEvent.getRawY() > lLocationBuffer[1] && pMotionEvent.getRawY() < lLocationBuffer[1] + lView.getHeight()) {
// Return the colliding View.
return lView;
}
}
// We couldn't find a colliding View.
return null;
}
Calls to getCollisionWith will return View references that may be manipulated arbitrarily.

Categories

Resources