I was working on Android Studio to create a simple app(game) and my problem is like: I've added two touch events for two separate views, if statement doesn't seem to work properly inside the touch event. Here's my code I would be so happy if you could help!
Here is MainActivity.java code:
package com.example.splitapp;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private RelativeLayout rel1 = null;
private RelativeLayout rel2 = null;
private int countA = 0;
private int countB = 0;
private boolean end = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rel1 = (RelativeLayout) findViewById(R.id.rel1);
rel2 = (RelativeLayout) findViewById(R.id.rel2);
rel1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(!end) {
countA = countA+1;
countB = countB-1;
if(countA == 10 && countB < 10){
rel1.setBackgroundColor(Color.parseColor("#00FF00"));
rel2.setBackgroundColor(Color.parseColor("#FF0000"));
end = true;
}
} else {
countA = 0;
countB = 0;
rel1.setBackgroundColor(Color.parseColor("#BA55D3"));
rel2.setBackgroundColor(Color.parseColor("#8A2BE2"));
end = false;
}
return true;
}
});
rel2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(!end) {
countB++;
countA--;
if(countB == 10 && countA < 10) {
rel1.setBackgroundColor(Color.parseColor("#FF0000"));
rel2.setBackgroundColor(Color.parseColor("#00FF00"));
end = true;
}
} else {
countA = 0;
countB = 0;
rel1.setBackgroundColor(Color.parseColor("#BA55D3"));
rel2.setBackgroundColor(Color.parseColor("#8A2BE2"));
end = false;
}
return true;
}
});
}
}
And here is my activity_main.xml 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:baselineAligned="false"
android:orientation="vertical"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/rel1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_weight="1"
android:background="#BA55D3"></RelativeLayout>
<RelativeLayout
android:id="@+id/rel2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#8A2BE2"></RelativeLayout>
</LinearLayout>
Aucun commentaire:
Enregistrer un commentaire