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
Related
As the title says,
When using startLabel.setVisibility(View.GONE);
The app Crashes and I am not sure how to fix
The Java code below.
public class Main extends AppCompatActivity {
private TextView scoreLabel;
private TextView startLabel;
private ImageView box;
private ImageView orange;
private ImageView pink;
private ImageView black;
// Position
private int boxY;
private int boxX;
// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Status Check
private boolean action_flg = false;
private boolean start_flg = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreLabel = (TextView) findViewById(R.id.scoreLabel);
scoreLabel = (TextView) findViewById(R.id.startLabel);
box = (ImageView) findViewById(R.id.box);
orange = (ImageView) findViewById(R.id.orange);
pink = (ImageView) findViewById(R.id.pink);
black = (ImageView) findViewById(R.id.black);
//Moves images to out of the screen
//orange.setX(-80.0f);
orange.setY(-80.0f);
// pink.setX(-80.0f);
pink.setY(-80.0f);
//black.setX(-80.0f);
black.setY(-80.0f);
boxY = 200;
}
public void changePos()
{
//Move box
if (action_flg == true)
{
// touching
boxY -= 20;
} else {
//released
boxY += 20;
}
box.setY(boxY);
}
public boolean onTouchEvent(MotionEvent me)
{
if (start_flg == false)
{
start_flg = true;
//Issue here with setting the visibility of the start
// startLabel.setVisibility(View.GONE);
timer.schedule(new TimerTask()
{
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
// Changing these numbers slows down how fast the box moves.
}, 0, 100);
}else {
if(me.getAction() == MotionEvent.ACTION_DOWN)
{
action_flg = true;
}else if (me.getAction() == MotionEvent.ACTION_UP){
action_flg = false;
}
}
return true;
}
}
Here is the XML version of the code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me.scott.nathan.catchtheball.Main">
<TextView
android:id="#+id/scoreLabel"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Score : 300"
android:textSize="18sp"
android:paddingLeft="10dp"
android:gravity="center_vertical">
</TextView>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/startLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tap to Start"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="130dp"
/>
<ImageView
android:id="#+id/box"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/box"
android:layout_gravity="center_vertical"
/>
<ImageView
android:id="#+id/orange"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/orange" />
<ImageView
android:id="#+id/black"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="#drawable/black" />
<ImageView
android:id="#+id/pink"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="#drawable/pink" />
</FrameLayout>
<!--
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.22" />
-->
</LinearLayout>
Anyone help appreciated to fix this issue, Thanks
Your startLabel is null (copy paste problem?^^). Replace this:
scoreLabel = (TextView) findViewById(R.id.startLabel);
with this:
startLabel = (TextView) findViewById(R.id.startLabel);
Hii i made a simple layout in which i use 3 image views and i make the center one movable.
Her is my layout class main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view class="com.example.screenlock.MainActivity$IV"
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|fill_horizontal"
android:background="#60000000"
android:orientation="horizontal"
android:padding="7dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:scaleType="fitXY"
android:layout_alignParentLeft="true"
android:src="#drawable/browser1" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/circle" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/lock" />
</LinearLayout>
</FrameLayout>
and My MainActivity.java class is as follows:-
public class MainActivity extends Activity {
private ImageView imageView1, imageView2;
public static class IV extends ImageView {
private MainActivity mActivity;
public IV(Context context) {
super(context);
}
public IV(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setActivity(MainActivity act) {
mActivity = act;
}
public void onSystemUiVisibilityChanged(int visibility) {
mActivity.getState().onSystemUiVisibilityChanged(visibility);
}
}
private interface State {
void apply();
State next();
void onSystemUiVisibilityChanged(int visibility);
}
State getState() {
return mState;
}
static int TOAST_LENGTH = 500;
IV mImage;
TextView mText1, mText2;
State mState;
public MainActivity() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyLockService.class));
System.out.println(R.id.image);
imageView2 = (ImageView)findViewById(R.id.imageView2);
imageView2.setOnTouchListener(new OnTouchListener()
{
float lastX;
PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
PointF StartPT = new PointF(); // Record Start Position of 'img'
#SuppressLint("NewApi")
#Override
public boolean onTouch(View v, MotionEvent event)
{
int eid = event.getAction();
switch (eid)
{
case MotionEvent.ACTION_MOVE :
PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD){
v.scrollBy((int) (event.getX()-lastX), 0);
lastX = event.getX();
if(lastX >= 170){
MarginLayoutParams lp = (MarginLayoutParams) imageView2.getLayoutParams();
lp.setMargins(178, 0, 0, 0);
imageView2.setLayoutParams(lp);
}
if(lastX <= 25){
MarginLayoutParams lp = (MarginLayoutParams) imageView2.getLayoutParams();
lp.setMargins(0, -16, 0, 0);
imageView2.setLayoutParams(lp);
}
System.out.println("XXXXXXX "+lastX);
}
else{
imageView2.setX((int)(StartPT.x+mv.x));
imageView2.setY((int)(StartPT.y+mv.y));
StartPT = new PointF( imageView2.getX(), imageView2.getY() );
//System.out.println("X: "+imageView2.getX()+"Y: "+imageView2.getY());
if(imageView2.getX() < -70)
{
imageView2.setX(-103);
imageView2.setY(6);
//System.out.println("--------------------------------------");
}
else if(imageView2.getX() > 260)
{
imageView2.setX(270);
imageView2.setY(8);
finish();
}
}
break;
case MotionEvent.ACTION_DOWN :
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD){
lastX = event.getX();
}
else{
DownPT.x = event.getX();
DownPT.y = event.getY();
StartPT = new PointF( imageView2.getX(), imageView2.getY() );
}
break;
case MotionEvent.ACTION_UP :
v.scrollTo(0, 0);
break;
default :
break;
}
return true;
}
});
}
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// Use onWindowFocusChanged to get the placement of
// the image because we have to wait until the image
// has actually been placed on the screen before we
// get the coordinates. That makes it impossible to
// do in onCreate, that would just give us (0, 0).
imageView1 = (ImageView) findViewById(R.id.imageView1);
int[] a = new int[2];
imageView1.getLocationInWindow(a);
int x = a[0];
int y = a[1];
System.out.println("X "+x+" Y "+y);
}
}
#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;
}
}
I am executing this code on pre-honeycomb emulator. But when i move the center image it gets hides behind the left and right images respectively.
I want center image to shown on the rest of two images and also want to show that two images also.
Basically, the center image is a circle and rest two images are browser and lock images and i want that circle to overlaps that images.
I am working on a lock screen.
Please help in my layout problem and how i can solve this problem?????
You can try changing your layout as follows...
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.screenlock.MainActivity$IV"
android:scaleType="center" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|fill_horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#60000000"
android:orientation="horizontal"
android:padding="7dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<View
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/ic_launcher" />
</FrameLayout>
</FrameLayout>
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 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>
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.