I am developing an android lock screen app. But now I am stuck. Basically I have a whole bunch of buttons on the screen, and I need to be able to register when they drag their finger from one button to the next, and in which order.
How can I do this?
I am trying to use the MotionEvent.ACTION_MOVE in the OnTouch method, but it isn't working. (It only works for button 1, as I am printing out to logcat the ID of the button that is being hovered over, but it wont print for any other button than button 1)
Please advise on how I can do this?
i do this one time, you need get all position of you view ( x and y with yourButton.getLeft() and yourButton.getTop() but be careful because you can get after layout creating don't use this in onCreate()) then in onTouch() method you have id of your button, in onTouch() method you can get position of finger with me.getX(), me.getY(), but this value have a relative with first view, so you must have something link this.
int rightXPos = yourButton.getLeft()+ me.getX() // yourButton is Button that
int rightYPos = yourButton.getTop()+ me.getY() // Toached firstTime
use log for catching me.getX(), me.getY() you understand your self.
then check the rightXPos and rightYPos with your list of position, then you can find out witch button touched
I hope that this useful for you
Edit
this is a sample code that do this, try this.
MainActivity.class
package activity;
import java.util.ArrayList;
import shayan.pourvatan.lowandhigh.R;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import farsiConverter.FarsiDigit;
public class MainActivity extends FragmentActivity implements OnClickListener , OnTouchListener {
ArrayList<Integer> _clickedPos;
ArrayList<Integer> _leftDestanceLine , _topDestanceLine;
TextView tv1 , tv2 , tv3 , tv4 , tv5 , tv6 , tv7 , tv8 , tv9;
TextView line1 , line2 , line3 , line4 , line5 , line6 , line7, line8;
TextView titleEn , titleFa;
boolean _firstTime;
int _count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
_clickedPos = new ArrayList<Integer>();
_leftDestanceLine = new ArrayList<Integer>();
_topDestanceLine = new ArrayList<Integer>();
InitializeTextView();
InitilizeLine();
// detector = new GestureDetector(this,this);
DefaultBackground();
_count = 0;
_firstTime = true;
}
private void InitilizeLine() {
line1 = (TextView) findViewById(R.id.textView21);
line2 = (TextView) findViewById(R.id.textView22);
line3 = (TextView) findViewById(R.id.textView23);
line4 = (TextView) findViewById(R.id.textView24);
line5 = (TextView) findViewById(R.id.textView25);
line6 = (TextView) findViewById(R.id.textView26);
line7 = (TextView) findViewById(R.id.textView27);
line8 = (TextView) findViewById(R.id.textView28);
}
private void InitializeTextView() {
tv1 = (TextView) findViewById(R.id.textView41);
tv2 = (TextView) findViewById(R.id.textView42);
tv3 = (TextView) findViewById(R.id.textView43);
tv4 = (TextView) findViewById(R.id.textView44);
tv5 = (TextView) findViewById(R.id.textView45);
tv6 = (TextView) findViewById(R.id.textView46);
tv7 = (TextView) findViewById(R.id.textView47);
tv8 = (TextView) findViewById(R.id.textView48);
tv9 = (TextView) findViewById(R.id.textView49);
titleEn = (TextView) findViewById(R.id.TitleEn);
titleFa = (TextView) findViewById(R.id.TitleFa);
tv1.setTag(1);
tv2.setTag(2);
tv3.setTag(3);
tv4.setTag(4);
tv5.setTag(5);
tv6.setTag(6);
tv7.setTag(7);
tv8.setTag(8);
tv9.setTag(9);
View main = findViewById(R.id.RelativeLayout1);
tv1.setOnClickListener(this);
tv2.setOnClickListener(this);
tv3.setOnClickListener(this);
tv4.setOnClickListener(this);
tv5.setOnClickListener(this);
tv6.setOnClickListener(this);
tv7.setOnClickListener(this);
tv8.setOnClickListener(this);
tv9.setOnClickListener(this);
tv1.setOnTouchListener(this);
tv2.setOnTouchListener(this);
tv3.setOnTouchListener(this);
tv4.setOnTouchListener(this);
tv5.setOnTouchListener(this);
tv6.setOnTouchListener(this);
tv7.setOnTouchListener(this);
tv8.setOnTouchListener(this);
tv9.setOnTouchListener(this);
main.setOnTouchListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void ChangingBackGround(int colorFrom , int colorTo, final View v) {
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
v.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
colorAnimation.start();
}
#Override
protected void onResume() {
overridePendingTransition(0,0);
super.onResume();
}
private void DefaultBackground() {
tv1.setBackgroundColor(Color.parseColor("#000000"));
tv3.setBackgroundColor(Color.parseColor("#000000"));
tv5.setBackgroundColor(Color.parseColor("#000000"));
tv7.setBackgroundColor(Color.parseColor("#000000"));
tv9.setBackgroundColor(Color.parseColor("#000000"));
tv2.setBackgroundColor(Color.parseColor("#ffffff"));
tv4.setBackgroundColor(Color.parseColor("#ffffff"));
tv6.setBackgroundColor(Color.parseColor("#ffffff"));
tv8.setBackgroundColor(Color.parseColor("#ffffff"));
}
private View GetViewPos(int _tempPos) {
switch (_tempPos) {
case 1: return tv1;
case 2: return tv2;
case 3: return tv3;
case 4: return tv4;
case 5: return tv5;
case 6: return tv6;
case 7: return tv7;
case 8: return tv8;
case 9: return tv9;
default:
break;
}
return null;
}
private int CheckPosition(float X, float Y) {
int pos = -1;
pos = Position1checked(X , Y);
pos = Position2checked(X , Y , pos);
pos = Position3checked(X , Y, pos);
pos = Position4checked(X , Y, pos);
pos = Position5checked(X , Y, pos);
pos = Position6checked(X , Y, pos);
pos = Position7checked(X , Y, pos);
pos = Position8checked(X , Y, pos);
pos = Position9checked(X , Y, pos);
return pos;
}
private int Position9checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(2) && x < _leftDestanceLine.get(3) &&
y > _topDestanceLine.get(2) && y < _topDestanceLine.get(3))
return 5;
return -1;
}
private int Position8checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(1) && x < _leftDestanceLine.get(2) &&
y > _topDestanceLine.get(2) && y < _topDestanceLine.get(3))
return 6;
return -1;
}
private int Position7checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(0) && x < _leftDestanceLine.get(1) &&
y > _topDestanceLine.get(2) && y < _topDestanceLine.get(3))
return 7;
return -1;
}
private int Position6checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(2) && x < _leftDestanceLine.get(3) &&
y > _topDestanceLine.get(1) && y < _topDestanceLine.get(2))
return 4;
return -1;
}
private int Position5checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(1) && x < _leftDestanceLine.get(2) &&
y > _topDestanceLine.get(1) && y < _topDestanceLine.get(2))
return 9;
return -1;
}
private int Position4checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(0) && x < _leftDestanceLine.get(1) &&
y > _topDestanceLine.get(1) && y < _topDestanceLine.get(2))
return 8;
return -1;
}
private int Position3checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(2) && x < _leftDestanceLine.get(3) &&
y > _topDestanceLine.get(0) && y < _topDestanceLine.get(1))
return 3;
return -1;
}
private int Position2checked(float x, float y, int pos) {
if (pos > -1)
return pos;
else
if (x > _leftDestanceLine.get(1) && x < _leftDestanceLine.get(2) &&
y > _topDestanceLine.get(0) && y < _topDestanceLine.get(1))
return 2;
return -1;
}
private int Position1checked(float x, float y) {
if (x > _leftDestanceLine.get(0) && x < _leftDestanceLine.get(1) &&
y > _topDestanceLine.get(0) && y < _topDestanceLine.get(1))
return 1;
return -1;
}
private void FillArrayPos() {
_leftDestanceLine.add(line1.getLeft());
_leftDestanceLine.add(line5.getLeft());
_leftDestanceLine.add(line6.getLeft());
_leftDestanceLine.add(line3.getLeft());
_topDestanceLine.add(line2.getTop());
_topDestanceLine.add(line7.getTop());
_topDestanceLine.add(line8.getTop());
_topDestanceLine.add(line4.getTop());
for (int i = 0 ; i < 4 ; i++)
{
Log.d(""+_leftDestanceLine.get(i),""+_topDestanceLine.get(i) );
}
_firstTime = false;
}
#Override
public boolean onTouch(View v, MotionEvent me) {
if (_firstTime)
FillArrayPos();
if (me.getActionMasked() == MotionEvent.ACTION_UP)
{
Log.d("in action up", "123");
// CheckEquality(_count);
// if _count == 1 then user just
}
int _tempPos = CheckPosition(me.getX()+v.getLeft() , me.getY()+v.getTop());
if (_clickedPos.size() > 0)
{
if (_tempPos == -1){}
else if (_tempPos == _clickedPos.get(_clickedPos.size()-1)){
//change the background of current position
}
else
{
_count++;
View v1 = GetViewPos(_tempPos);
ChangingBackGround(Color.parseColor("#ffffff") , Color.parseColor("#ffa500") , v1 );
_clickedPos.add(_tempPos);
}
}
else
{
if (_tempPos == -1){}
else
{
_count++;
View v1 = GetViewPos(_tempPos);
ChangingBackGround(Color.parseColor("#ffffff") , Color.parseColor("#ffa500") , v1 );
_clickedPos.add(_tempPos);
}
}
return true;
}
}
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical" >
<TextView
android:id="#+id/TitleEn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/TitleFa"
android:layout_below="#+id/TitleFa"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textSize="18sp" />
<TextView
android:id="#+id/TitleFa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffa500"
android:textSize="40sp" />
<TextView
android:id="#+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#000" />
<TextView
android:id="#+id/textView25"
android:layout_width="2dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView24"
android:layout_alignTop="#+id/textView22"
android:layout_marginRight="45dp"
android:layout_toLeftOf="#+id/textView17"
android:background="#000" />
<TextView
android:id="#+id/textView21"
android:layout_width="2dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView24"
android:layout_alignTop="#+id/textView22"
android:layout_marginRight="90dp"
android:layout_toLeftOf="#+id/textView25"
android:background="#000" />
<TextView
android:id="#+id/textView26"
android:layout_width="2dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView24"
android:layout_alignTop="#+id/textView22"
android:layout_marginLeft="45dp"
android:layout_toRightOf="#+id/textView17"
android:background="#000" />
<TextView
android:id="#+id/textView23"
android:layout_width="2dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView24"
android:layout_alignTop="#+id/textView22"
android:layout_marginLeft="90dp"
android:layout_toRightOf="#+id/textView26"
android:background="#000" />
<TextView
android:id="#+id/textView24"
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_above="#+id/textView17"
android:layout_alignLeft="#+id/textView21"
android:layout_alignRight="#+id/textView23"
android:layout_marginBottom="5dp"
android:background="#000" />
<TextView
android:id="#+id/textView28"
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_above="#+id/textView24"
android:layout_alignLeft="#+id/textView24"
android:layout_alignRight="#+id/textView23"
android:layout_marginBottom="90dp"
android:background="#000" />
<TextView
android:id="#+id/textView27"
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_above="#+id/textView28"
android:layout_alignLeft="#+id/textView28"
android:layout_alignRight="#+id/textView23"
android:layout_marginBottom="90dp"
android:background="#000" />
<TextView
android:id="#+id/textView22"
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_above="#+id/textView27"
android:layout_alignLeft="#+id/textView21"
android:layout_alignRight="#+id/textView23"
android:layout_marginBottom="90dp"
android:background="#000" />
<TextView
android:id="#+id/textView41"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView27"
android:layout_alignLeft="#+id/textView22"
android:layout_alignRight="#+id/textView25"
android:layout_alignTop="#+id/textView25"
android:layout_marginBottom="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:layout_toLeftOf="#+id/textView25"
android:background="#000"
android:gravity="center"
android:text="1"
android:textColor="#fff"
android:textSize="50sp" />
<TextView
android:id="#+id/textView43"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView27"
android:layout_alignLeft="#+id/textView26"
android:layout_alignRight="#+id/textView23"
android:layout_alignTop="#+id/textView23"
android:layout_marginBottom="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="#000"
android:gravity="center"
android:text="3"
android:textColor="#fff"
android:textSize="50sp" />
<TextView
android:id="#+id/textView47"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView21"
android:layout_alignLeft="#+id/textView28"
android:layout_alignRight="#+id/textView41"
android:layout_alignTop="#+id/textView45"
android:layout_marginBottom="2dp"
android:layout_marginLeft="2dp"
android:background="#000"
android:gravity="center"
android:text="7"
android:textColor="#fff"
android:textSize="50sp" />
<TextView
android:id="#+id/textView45"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView26"
android:layout_alignLeft="#+id/textView43"
android:layout_alignRight="#+id/textView28"
android:layout_alignTop="#+id/textView28"
android:layout_marginBottom="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="#000"
android:gravity="center"
android:text="9"
android:textColor="#fff"
android:textSize="50sp" />
<TextView
android:id="#+id/textView42"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView27"
android:layout_alignTop="#+id/textView41"
android:layout_toLeftOf="#+id/textView43"
android:layout_toRightOf="#+id/textView41"
android:background="#fff"
android:gravity="center"
android:text="2"
android:textColor="#000"
android:textSize="50sp" />
<TextView
android:id="#+id/textView48"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView28"
android:layout_alignLeft="#+id/textView41"
android:layout_alignRight="#+id/textView41"
android:layout_below="#+id/textView41"
android:background="#fff"
android:gravity="center"
android:text="4"
android:textColor="#000"
android:textSize="50sp" />
<TextView
android:id="#+id/textView49"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView48"
android:layout_alignRight="#+id/textView42"
android:layout_below="#+id/textView41"
android:layout_toRightOf="#+id/textView41"
android:background="#000"
android:gravity="center"
android:text="5"
android:textColor="#fff"
android:textSize="50sp" />
<TextView
android:id="#+id/textView44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView49"
android:layout_alignLeft="#+id/textView43"
android:layout_alignRight="#+id/textView43"
android:layout_alignTop="#+id/textView49"
android:background="#fff"
android:gravity="center"
android:text="6"
android:textColor="#000"
android:textSize="50sp" />
<TextView
android:id="#+id/textView46"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView24"
android:layout_alignLeft="#+id/textView49"
android:layout_alignRight="#+id/textView49"
android:layout_alignTop="#+id/textView47"
android:background="#fff"
android:gravity="center"
android:text="8"
android:textColor="#000"
android:textSize="50sp" />
</RelativeLayout>
Related
This app translates form specific graffiti shapes to text.
I have 3 categories, letters, numbers and other characters.
The starting point defines the category to choose the output from. It works will on the emulator but with changing phones (resolution) it starts to get wrong.
This is my activity for drawing the graffiti and the TextView that show the result.
This is the activity XML:
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.soltan.app1.MainActivity"
android:background="#0e004e"
android:animateLayoutChanges="false"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/res"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#ffffff"
android:textDirection="anyRtl"
android:hint="#string/mess"
android:layout_above="#+id/chars" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="105dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#ffffff"
android:layout_marginTop="5dp"
android:id="#+id/letters"
android
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/txt3"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textDirection="anyRtl"
android:hint="#string/txt3" />
</RelativeLayout>
<RelativeLayout
android:layout_width="175dp"
android:layout_height="90dp"
android:layout_above="#+id/letters"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#ffffff"
android:layout_marginTop="5dp"
android:id="#+id/chars"
android:layout_alignParentRight="false"
android:layout_marginRight="5dp"
android:layout_alignParentEnd="false"
android:focusable="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/txt1"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textDirection="anyRtl"
android:hint="#string/txt1" />
</RelativeLayout>
<RelativeLayout
android:layout_width="175dp"
android:layout_height="90dp"
android:layout_above="#+id/letters"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#fff"
android:layout_toRightOf="#+id/chars"
android:id="#+id/numbers">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/txt2"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textDirection="anyRtl"
android:hint="#string/txt2" />
</RelativeLayout>
</RelativeLayout>
This is how I choose the category for now i the java file:
private List<Point> input; // a list contains the drawn graffiti shape coordinates
private Input inserted; // instance of a class
String section; // the category from which we receive the output
boolean proceed ; // if the starting point in the allowed range
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onTouchEvent(MotionEvent touchEvent)
{
super.onTouchEvent(touchEvent);
switch(touchEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
input = new ArrayList<>();
if(touchEvent.getY() < 1216)
{
proceed = false;
}
else if(touchEvent.getY() > 1465)
{
proceed = true;
section = "letter";
}
else if(touchEvent.getX() < 506)
{
proceed = true;
section = "char";
}
else
{
proceed = true;
section = "number";
}
//Inserting the touch event points into the array list of points
for (int h = 0; h < touchEvent.getHistorySize(); h++)
{
for (int p = 0; p < touchEvent.getPointerCount(); p++)
{
float x = touchEvent.getHistoricalX(p,h);
float y = touchEvent.getHistoricalY(p,h);
input.add(new Point(x,y));
}
}
break;
}
case MotionEvent.ACTION_MOVE:
{
//Inserting the touch event points into the array list of points
for (int h = 0; h < touchEvent.getHistorySize(); h++)
{
for (int p = 0; p < touchEvent.getPointerCount(); p++)
{
float x = touchEvent.getHistoricalX(p,h);
float y = touchEvent.getHistoricalY(p,h);
input.add(new Point(x,y));
}
}
break;
}
case MotionEvent.ACTION_UP:
{
//Inserting the touch event points into the array list of points
for (int h = 0; h < touchEvent.getHistorySize(); h++)
{
for (int p = 0; p < touchEvent.getPointerCount(); p++)
{
float x = touchEvent.getHistoricalX(p,h);
float y = touchEvent.getHistoricalY(p,h);
input.add(new Point(x,y));
}
}
if(proceed)
{
inserted = new Input();
String letter =inserted.checkPoint(input,section);
if(letter.equals(""))
{
Toast.makeText(this,"No Such Graffiti, check the our dictionary!",Toast.LENGTH_SHORT).show();
}
TextView myText =(TextView) findViewById(R.id.res);
String text = myText.getText().toString();
myText.setText(text+letter);
}
break;
}
}
return true;
}
it looks to me that you're trying to get the touchEvents from the topmost view and according to the coordinates determine which child is touched? If so this is very wrong. The way to go is to register for the children themselves the onClick or onTouch listener and just check the view's id in there to determine which one was touched.
Edit:
The easiest way to do this is to add this to all three RelativeLayouts that you gave an id:
android:onClick="myMethod"
And then add this in your activity
public void myMethod(View view) {
switch(view.getId()) {
case R.id.letters:
//do here what you wanna do with letters
break;
case R.id.chars:
//do here what you wanna do with chars
break;
case R.id.numbers:
//do here what you wanna do with numbers
break;
}
}
you can of course rename the method as you like as long as it is the same as you specified in the xml
I'm creating a small application for practice some in Android programming. It's a kind of puzzle game like this:
Screen from application
I have a following issue: when I slide a button left or right in x property all is OK. I can move each button frequently left and right. The problem begins when I move the button down or up in y property. I can only move the button once and next it will be no longer available for the onTouchListener. It become immobile in any direction and any action isn't performed. Here is my java activity file and the layout xml.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
class MyPoint{
private boolean canMove;
private View associatedView;
private int x;
private int y;
private MyPoint nord;
private MyPoint south;
private MyPoint est;
private MyPoint west;
MyPoint(int x, int y, View associatedView){
this.x = x;
this.y = y;
this.associatedView = associatedView;
canMove = false;
}
public MyPoint getEst() {
return est;
}
public MyPoint getNord() {
return nord;
}
public MyPoint getSouth() {
return south;
}
public MyPoint getWest() {
return west;
}
public void setNeighbors(MyPoint nord, MyPoint south, MyPoint west, MyPoint est){
this.nord = nord;
this.south = south;
this.est = est;
this.west = west;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public View getAssociatedView() {
return associatedView;
}
public void setAssociatedView(View associatedView) {
this.associatedView = associatedView;
}
public boolean isSpace(){
if(associatedView.getId() == R.id.space)
return true;
else
return false;
}
public void allowMovement(){
canMove = true;
}
public void denyMovement(){
canMove = false;
}
public void allowMovementNeighbords(){
nord.allowMovement();
south.allowMovement();
est.allowMovement();
west.allowMovement();
}
public boolean isMoveable(){
if(canMove) return true;
else return false;
}
}
public class MainActivity extends ActionBarActivity {
LinearLayout mainScreen;
MyPoint[] board = new MyPoint[16];
View[] views = new View[16];
View blank;
MyPoint blankPoint, associatedPoint;
int DX,DY;
private MyPoint findPointByView(View target){
MyPoint tempResult = blankPoint;
for(int i=0; i<16; i++)
if(board[i].getAssociatedView().getId() == target.getId())
tempResult = board[i];
return tempResult;
}
private MyPoint findSpace(){
MyPoint tempResult = blankPoint;
for(int i=0; i<16; i++)
if(board[i].isSpace()){
tempResult = board[i];
}
return tempResult;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainScreen = (LinearLayout) findViewById(R.id.main_screen);
blank = findViewById(R.id.blank);
blankPoint = new MyPoint(0,0,blank);
blankPoint.setNeighbors(blankPoint,blankPoint,blankPoint,blankPoint);
associatedPoint = blankPoint;
final View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event){
float x1=0, x2, y1=0, y2, dx, dy;
switch(event.getActionMasked()) {
case(MotionEvent.ACTION_DOWN):
associatedPoint = findPointByView(v);
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(associatedPoint.isMoveable()){
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0){
if(associatedPoint.getEst().isSpace()){
v.animate().xBy(DX);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getEst().setAssociatedView(v);
}
}
else{
if(associatedPoint.getWest().isSpace()){
v.animate().xBy(-DX);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getWest().setAssociatedView(v);
}
}
} else {
if(dy>0){
if(associatedPoint.getSouth().isSpace()){
v.animate().yBy(DY);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getSouth().setAssociatedView(v);
}
}
else{
if(associatedPoint.getNord().isSpace()){
v.animate().yBy(-DY);
associatedPoint.setAssociatedView(findViewById(R.id.space));
associatedPoint.getNord().setAssociatedView(v);
}
}
}
denyMovementAll();
findSpace().allowMovementNeighbords();
}
return true;
}
}
return false;
}
};
views[0] = findViewById(R.id.button1);
views[1] = findViewById(R.id.button2);
views[2] = findViewById(R.id.button3);
views[3] = findViewById(R.id.button4);
views[4] = findViewById(R.id.button5);
views[5] = findViewById(R.id.button6);
views[6] = findViewById(R.id.button7);
views[7] = findViewById(R.id.button8);
views[8] = findViewById(R.id.button9);
views[9] = findViewById(R.id.button10);
views[10] = findViewById(R.id.button11);
views[11] = findViewById(R.id.button12);
views[12] = findViewById(R.id.button13);
views[13] = findViewById(R.id.button14);
views[14] = findViewById(R.id.button15);
views[15] = findViewById(R.id.space);
for(int i=0; i<15; i++)
views[i].setOnTouchListener(mTouchListener);
}
private void denyMovementAll() {
for(int i=0; i<16; i++)
board[i].denyMovement();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int offsetY = displayMetrics.heightPixels - mainScreen.getMeasuredHeight();
for (int i=0 ; i<16; i++){
int[] tempCoords = new int[2];
views[i].getLocationOnScreen(tempCoords);
int x = tempCoords[0];
int y = tempCoords[1] - offsetY;
board[i] = new MyPoint(x,y,views[i]);
}
board[0].setNeighbors(blankPoint,board[4],blankPoint,board[1]);
board[1].setNeighbors(blankPoint,board[5],board[0],board[2]);
board[2].setNeighbors(blankPoint,board[6],board[1],board[3]);
board[3].setNeighbors(blankPoint,board[7],board[2],blankPoint);
board[4].setNeighbors(board[0],board[8],blankPoint,board[5]);
board[5].setNeighbors(board[1],board[9],board[4],board[6]);
board[6].setNeighbors(board[2],board[10],board[5],board[7]);
board[7].setNeighbors(board[3],board[11],board[6],blankPoint);
board[8].setNeighbors(board[4],board[12],blankPoint,board[9]);
board[9].setNeighbors(board[5],board[13],board[8],board[10]);
board[10].setNeighbors(board[6],board[14],board[9],board[11]);
board[11].setNeighbors(board[7],board[15],board[10],blankPoint);
board[12].setNeighbors(board[8],blankPoint,blankPoint,board[13]);
board[13].setNeighbors(board[9],blankPoint,board[12],board[14]);
board[14].setNeighbors(board[10],blankPoint,board[13],board[15]);
board[15].setNeighbors(board[11],blankPoint,board[14],blankPoint);
DX = board[1].getX() - board[0].getX();
DY = board[4].getY() - board[0].getY();
denyMovementAll();
findSpace().allowMovementNeighbords();
}
}
activity_main.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:collapseColumns="4"
android:orientation="vertical"
android:clipChildren="false"
android:id="#+id/main_screen"
android:clipToPadding="false">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row1">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b1"
android:id="#+id/button1"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b2"
android:id="#+id/button2"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b3"
android:id="#+id/button3"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b4"
android:id="#+id/button4"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row2">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b5"
android:id="#+id/button5"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b6"
android:id="#+id/button6"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b7"
android:id="#+id/button7"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b8"
android:id="#+id/button8"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row3">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b9"
android:id="#+id/button9"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b10"
android:id="#+id/button10"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b11"
android:id="#+id/button11"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b12"
android:id="#+id/button12"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipChildren="false"
android:clipToPadding="false"
android:id="#+id/row4">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b13"
android:id="#+id/button13"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b14"
android:id="#+id/button14"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="#string/b15"
android:id="#+id/button15"
android:layout_weight="1" />
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/space"
android:visibility="invisible"/>
<Space
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
android:id="#+id/blank"/>
</LinearLayout>
</LinearLayout>
I have really no idea what cause this problem. Please give me a small prompt on what may cause this issue. Thanks in advance
You should return true if the listener has consumed the event. Otherwise, it should return false as default.
View.OnTouchListener mTouchListener = new View.OnTouchListener() {
...
return false;
}
I changed my code following your tip :
View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event){
float x1=0, x2, y1=0, y2, dx, dy;
switch(event.getActionMasked()) {
case(MotionEvent.ACTION_DOWN):
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0){
v.animate().xBy(DX);
}
else{
v.animate().xBy(-DX);
}
} else {
if(dy>0){
v.animate().yBy(DY);
}
else{
v.animate().yBy(-DY);
}
}
return true;
}
}
return false;
}
};
Unfortunately, that doesn't solve my problem. Please, correct me if I made a mistake
I have 4 buttons in my android app activity. This is what it looks like:
As you can see, the textViews at the bottom of the screen display the x and y coordinates. The coordinates are in reference to a relative layout. (See below given code)
Now, what I want to do is get the x and y coordinates of the 4 buttons at runtime and then figure out if my finger is touching the buttons while moving or not. In simple words, I want to press the buttons by swiping my finger over them instead of lifting and touching. How can I achieve it? I want to implement it in my piano application.
I was able to get the coordinates on screen and they change as I move my finger.
So, my question is How can I get the coordinates of the buttons and detect if my finger is swiping above them?:
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:id="#+id/relativelayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Y Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="X Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView2"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"
android:textColor="#000000"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView4"
android:textColor="#000000"
android:layout_marginBottom="10dp"
android:layout_above="#+id/textView"
android:layout_toRightOf="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:textColor="#000000"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button4"
android:textColor="#000000"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
RelativeLayout touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
});
}
}
Thank you all very very much!
Update:
public class MainActivity extends Activity {
RelativeLayout touchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
Button button = (Button) findViewById(R.id.button);
button.setBackgroundColor(Color.BLUE);
break;
}
}
return true;
}
});
}
private boolean checkInterSection(View view, float rawX, float rawY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
}
package com.example.touch;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b1, b2, b3, b4;
int b1x1, b1x2, b1y1, b1y2;
private TextView xcordview;
private TextView ycordview;
private TextView buttonIndicator;
private RelativeLayout touchview;
private static int defaultStates[];
private Button mLastButton;
private final static int[] STATE_PRESSED = {
android.R.attr.state_pressed,
android.R.attr.state_focused
| android.R.attr.state_enabled };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xcordview = (TextView) findViewById(R.id.textView4);
ycordview = (TextView) findViewById(R.id.textView3);
buttonIndicator = (TextView) findViewById(R.id.button_indicator);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
defaultStates = b1.getBackground().getState();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
touchview.setOnTouchListener(new View.OnTouchListener() {
private boolean isInside = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
xcordview.setText(String.valueOf(x));
ycordview.setText(String.valueOf(y));
for (int i = 0; i < touchview.getChildCount(); i++) {
View current = touchview.getChildAt(i);
if (current instanceof Button) {
Button b = (Button) current;
if (!isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(defaultStates);
}
if (isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(STATE_PRESSED);
if (b != mLastButton) {
mLastButton = b;
buttonIndicator.setText(mLastButton.getText());
}
}
}
}
return true;
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
}
static boolean isPointWithin(int x, int y, int x1, int x2, int y1, int y2) {
return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}
}
layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="Y Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="X Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="B1"
android:textColor="#000000" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:text="B2"
android:textColor="#000000" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button2"
android:text="B3"
android:textColor="#000000" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button3"
android:text="B4"
android:textColor="#000000" />
<TextView
android:id="#+id/button_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView4"
android:layout_marginRight="33dp"
android:text="No one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button_indicator"
android:layout_alignBottom="#+id/button_indicator"
android:layout_marginRight="29dp"
android:layout_toLeftOf="#+id/button_indicator"
android:text="Entered: "
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
private boolean checkInterSection(View view, int rawX, int raxY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.BLUE);// Type casting may not be required
}else{
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.WHITE);
}
break;
}
}
getX() getY() for a OnTouchListener give coordinates relative the the cooresponding view.
If you prefer screen coordinates instead you can use one of the following
overwrite onTouchEvent for the activity and remove OnTouchListener-s for buttons,
in which case MotionEvent will report screen coordinates instead of Button coordinates
#Override
public boolean onTouchEvent (MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
use getTop() getLeft() in OnTouchListener for a button:
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()+v.getLeft()));
ycordview.setText(String.valueOf(event.getY()+v.getTop()));
return true;
}
});
You may consider using GestureDetector to detect swipes, however it isn't really necessary.
karioki 's solution works well. In order to make it work even when we start the move from inside one of the buttons, just add
android:clickable="false"
for every button in xml.
I have a problem with horizontal scroll view.
This is my XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relative_layout_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home_title_id"
android:text="#string/home_title"
android:layout_marginTop="#dimen/forty_text_size"
android:textColor="#android:color/white"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="#dimen/forty_text_size" />
<LinearLayout
android:id="#+id/linear_layout_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/home_title_id">
<HorizontalScrollView
android:id="#+id/horizontal_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/home_image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc" />
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
In my Java class, extending activity I have declared all the widgets, then i created a class scrollview, extending horizontal scroll view.
The Java code is as follows:
class scrollview extends HorizontalScrollView
{
private static final int SWIPE_MIN_DISTANCE = 5;
private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private ArrayList mItems = null;
private GestureDetector mGestureDetector;
private int mActiveFeature = 0;
public scrollview(Context context)
{
super(context);
}
public void setFeatureItems(ArrayList items)
{
LinearLayout internalWrapper = new LinearLayout(getContext());
internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
addView(internalWrapper);
this.mItems = items;
for(int i = 0; i< items.size();i++)
{
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.activity_main,null);
//...
//Create the view for each screen in the scroll view
//...
internalWrapper.addView(featureLayout);
}
setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
//If the user swipes
if (mGestureDetector.onTouchEvent(event))
{
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL )
{
int scrollX = getScrollX();
int featureWidth = v.getMeasuredWidth();
mActiveFeature = ((scrollX + (featureWidth/2))/featureWidth);
int scrollTo = mActiveFeature*featureWidth;
smoothScrollTo(scrollTo, 0);
return true;
}
else
{
return false;
}
}
});
mGestureDetector = new GestureDetector(new MyGestureDetector());
}
class MyGestureDetector extends SimpleOnGestureListener
{
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
try
{
//right to left
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
//left to right
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
int featureWidth = getMeasuredWidth();
mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
smoothScrollTo(mActiveFeature*featureWidth, 0);
return true;
}
} catch (Exception e) {
Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
}
return false;
}
}
}
But nothing happens, please help.
ORWILL IT BE BETTER TO HAVE THE SCROLL CLASS IN THE ONTOUCH LISTNER FUNCTION???
Wrong tag placement in your layout.xml file i think. Place LinearLayout having ImageView in HorizontalScrollView instead of HorizontalScrollView in LinearLayout as below:
<HorizontalScrollView
android:id="#+id/horizontal_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/home_title_id" >
<LinearLayout
android:id="#+id/linear_layout_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/home_image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc" />
</LinearLayout>
</HorizontalScrollView>
there is no need for java coding here. this java coding is required only for SWIPE functionality
the XML coding alone is enough!!!but, in the following format
<HorizontalScrollView
android:id="#+id/horizontal_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/home_title_id" >
<LinearLayout
android:id="#+id/linear_layout_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/home_image_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc" />
</LinearLayout>
</HorizontalScrollView>
as horizontal scroll can hold only one child node.
I have an integer ArrayList and several buttons. Each button corresponds to an index of the ArrayList and I want to display the value of each button's corresponding index as its text. I have everything working with button behavior, etc. The problem is when I go to swap a button's value (index value) with another it will start to display 0s for every value I swap it with. I am always going to be swapping the 0 with something else.
So if I have buttons: b1, b2, b3 with values 0, 1, 2 respectively and I swap the values of b1 and b2. The result becomes 0, 0, 2. This is the swapping function:
public static void swap(ArrayList<Integer> list, int firstInd, int secondInd) {
int temp = list.get(firstInd);
list.set(firstInd, list.get(secondInd));
list.set(secondInd, temp);
}
This swap method works, I have tested it independently using print statements, etc. and there are no duplicate 0s and all of the rest of the numbers remain in the list.
Here is the relevant code:
// class declaration
static ArrayList<Integer> numList = new ArrayList<Integer>();
// onCreate
// initialize ArrayList
// displays initial values on buttons
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.first: {
switchButtonValues(R.id.first);
b1.setText(String.valueOf(numList.get(0)));
updateButtonStates();
break;
}
case R.id.second: {
switchButtonValues(R.id.second);
b2.setText(String.valueOf(numList.get(1)));
updateButtonStates();
break;
}
// etc for all buttons
public static void switchButtonValues(int buttonNum) {
switch(buttonNum) {
case R.id.first: {
if(numList.get(1) == 0) {
swap(numList, 0, 1);
} else if (numList.get(3) == 0) {
swap(numList, 0, 3);
} else {
}
break;
}
case R.id.second: {
// etc. for the buttons
The buttons displaying the initial values is correct. So I know the ArrayList is getting initialized properly. The problem occurs when the swapping occurs. All of the values are getting overwritten with 0 somehow.
Even though 0s are overwriting the other values, the button behavior is working correctly because it knows where the "real" 0 is. I have cleaned the project too.
Why is this happening? Anyone have any ideas?
I did an example, I hope it's near what you expect:
package br.com.bertan.swap.buttons;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SwapButtonsActivity extends Activity {
// class declaration
static ArrayList<Integer> numList = new ArrayList<Integer>();
static ArrayList<Button> btnList = new ArrayList<Button>();
public static void swap(ArrayList<Integer> list, int firstInd, int secondInd) {
int temp = list.get(firstInd);
list.set(firstInd, list.get(secondInd));
list.set(secondInd, temp);
}
private void updateButtonStates(){
int index_0 = -1;
int index_up = -1;
int index_down = -1;
int index_left = -1;
int index_right = -1;
for(int i = 0; i < 16; i++){
if(index_0 >= 0){
if(i != index_up
&& i != index_down
&& i != index_left
&& i != index_right
// && i != index_0
){
btnList.get(i).setEnabled(false);
} else {
btnList.get(i).setEnabled(true);
}
} else {
if(numList.get(i) == 0){
index_0 = i;
if(index_0 > 3){
index_up = index_0 - 4;
}
if(index_0 < 12){
index_down = index_0 + 4;
}
if(index_0 != 0
&& index_0 != 4
&& index_0 != 8
&& index_0 != 12){
index_left = index_0 - 1;
}
if(index_0 != 3
&& index_0 != 7
&& index_0 != 11
&& index_0 != 15){
index_right = index_0 + 1;
}
i = -1;
}
}
}
}
public static void switchButtonValues(int buttonNum) {
int index_0 = -1;
int index_btn = -1;
for(int i = 0; i < 16; i++){
if(index_0 < 0){
if(numList.get(i) == 0){
index_0 = i;
}
}
if(index_btn < 0){
if(buttonNum == btnList.get(i).getId()){
index_btn = i;
}
}
if(index_0 >= 0 && index_btn >=0){
break;
}
}
btnList.get(index_0).setText(btnList.get(index_btn).getText().toString());
btnList.get(index_btn).setText("0");
numList.set(index_0, numList.get(index_btn));
numList.set(index_btn, 0);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// initialize ArrayList
for(int i = 0; i < 16; i++){
numList.add(i);
}
final Button btn_01 = (Button) findViewById(R.id.btn_01);
final Button btn_02 = (Button) findViewById(R.id.btn_02);
final Button btn_03 = (Button) findViewById(R.id.btn_03);
final Button btn_04 = (Button) findViewById(R.id.btn_04);
final Button btn_05 = (Button) findViewById(R.id.btn_05);
final Button btn_06 = (Button) findViewById(R.id.btn_06);
final Button btn_07 = (Button) findViewById(R.id.btn_07);
final Button btn_08 = (Button) findViewById(R.id.btn_08);
final Button btn_09 = (Button) findViewById(R.id.btn_09);
final Button btn_10 = (Button) findViewById(R.id.btn_10);
final Button btn_11 = (Button) findViewById(R.id.btn_11);
final Button btn_12 = (Button) findViewById(R.id.btn_12);
final Button btn_13 = (Button) findViewById(R.id.btn_13);
final Button btn_14 = (Button) findViewById(R.id.btn_14);
final Button btn_15 = (Button) findViewById(R.id.btn_15);
final Button btn_16 = (Button) findViewById(R.id.btn_16);
btnList.add(btn_01);
btnList.add(btn_02);
btnList.add(btn_03);
btnList.add(btn_04);
btnList.add(btn_05);
btnList.add(btn_06);
btnList.add(btn_07);
btnList.add(btn_08);
btnList.add(btn_09);
btnList.add(btn_10);
btnList.add(btn_11);
btnList.add(btn_12);
btnList.add(btn_13);
btnList.add(btn_14);
btnList.add(btn_15);
btnList.add(btn_16);
OnClickListener click_listener = new OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn_01: {
switchButtonValues(R.id.btn_01);
btn_01.setText(String.valueOf(numList.get(0)));
updateButtonStates();
break;
}
case R.id.btn_02: {
switchButtonValues(R.id.btn_02);
btn_02.setText(String.valueOf(numList.get(1)));
updateButtonStates();
break;
}
case R.id.btn_03: {
switchButtonValues(R.id.btn_03);
btn_03.setText(String.valueOf(numList.get(2)));
updateButtonStates();
break;
}
case R.id.btn_04: {
switchButtonValues(R.id.btn_04);
btn_04.setText(String.valueOf(numList.get(3)));
updateButtonStates();
break;
}
case R.id.btn_05: {
switchButtonValues(R.id.btn_05);
btn_05.setText(String.valueOf(numList.get(4)));
updateButtonStates();
break;
}
case R.id.btn_06: {
switchButtonValues(R.id.btn_06);
btn_06.setText(String.valueOf(numList.get(5)));
updateButtonStates();
break;
}
case R.id.btn_07: {
switchButtonValues(R.id.btn_07);
btn_07.setText(String.valueOf(numList.get(6)));
updateButtonStates();
break;
}
case R.id.btn_08: {
switchButtonValues(R.id.btn_08);
btn_08.setText(String.valueOf(numList.get(7)));
updateButtonStates();
break;
}
case R.id.btn_09: {
switchButtonValues(R.id.btn_09);
btn_09.setText(String.valueOf(numList.get(8)));
updateButtonStates();
break;
}
case R.id.btn_10: {
switchButtonValues(R.id.btn_10);
btn_10.setText(String.valueOf(numList.get(9)));
updateButtonStates();
break;
}
case R.id.btn_11: {
switchButtonValues(R.id.btn_11);
btn_11.setText(String.valueOf(numList.get(10)));
updateButtonStates();
break;
}
case R.id.btn_12: {
switchButtonValues(R.id.btn_12);
btn_12.setText(String.valueOf(numList.get(11)));
updateButtonStates();
break;
}
case R.id.btn_13: {
switchButtonValues(R.id.btn_13);
btn_13.setText(String.valueOf(numList.get(12)));
updateButtonStates();
break;
}
case R.id.btn_14: {
switchButtonValues(R.id.btn_14);
btn_14.setText(String.valueOf(numList.get(13)));
updateButtonStates();
break;
}
case R.id.btn_15: {
switchButtonValues(R.id.btn_15);
btn_15.setText(String.valueOf(numList.get(14)));
updateButtonStates();
break;
}
case R.id.btn_16: {
switchButtonValues(R.id.btn_16);
btn_16.setText(String.valueOf(numList.get(15)));
updateButtonStates();
break;
}
default:
break;
}
}
};
// displays initial values on buttons
for(int i = 0; i < 16; i++){
btnList.get(i).setText(String.valueOf(numList.get(i)));
btnList.get(i).setOnClickListener(click_listener);
}
updateButtonStates();
}
}
And here is my layout:
<?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">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/btn_01"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="0"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_02"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="1"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_03"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="2"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_04"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="3"
android:textSize="50dip"
android:textStyle="bold"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/btn_05"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="4"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_06"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="5"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_07"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="6"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_08"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="7"
android:textSize="50dip"
android:textStyle="bold"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/btn_09"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="8"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_10"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="9"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_11"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="10"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_12"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="11"
android:textSize="50dip"
android:textStyle="bold"
/>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/btn_13"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="12"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_14"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="13"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_15"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="14"
android:textSize="50dip"
android:textStyle="bold"
/>
<Button
android:id="#+id/btn_16"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="15"
android:textSize="50dip"
android:textStyle="bold"
/>
</TableRow>
</TableLayout>
</LinearLayout>
that's worked just fine, and really quite a funny when you shuffle the places and try to put then in order... hehehe
It's simple and was one good idea for a game :D (I will do some sort of this genre and let see what happens)
I think that's possible to better the code, I had suspect of this part of your code:
case R.id.btn_01: {
switchButtonValues(R.id.btn_01);
btn_01.setText(String.valueOf(numList.get(0)));
updateButtonStates();
break;
}
I thinked you switch the values, and next set the text with the numList value of that position, but, you had changed with the 0, isn't? Maybe it's your problem, try put the line that set the text before the switch...
cya,
Bertan.