Validate string with parse - android

I am trying to validate 3 values, one that is entered manually and the other two are selected with the picker, in the end it is not validated and an error appears, I need that when the user has not entered any value, an alert pops up saying that all fields must be completed, but I can't see how to implement it.
void CalculateBMI(object sender, EventArgs e)
{
double weight = Double.Parse(peso.Text);
double feets = Double.Parse(Pies.SelectedItem.ToString());
double inches = Double.Parse(Pulgadas.SelectedItem.ToString());
double totalInches = (feets * 12) + inches;
double bmi = (weight * 703) / (totalInches * totalInches);
lblBMIValue.Text = String.Format("Your BMI is {0:0.00}", bmi);
string bmiLevel = "";
Color color = Color.Transparent;
lblBMI.TextColor = Color.White;
if ((weight <= 0) || (inches <= 0) || (feets <= 0))
{
DisplayAlert("Attention", "Please complete all the data.", "Ok");
return;
}
else if (bmi < 18.5)
{
bmiLevel = "Underweight"; color = Color.FromHex("FECD57");
}
else if (bmi < 25)
{
bmiLevel = "Normal"; color = Color.FromHex("1287CE");
}
else if (bmi < 30)
{
bmiLevel = "Overweight"; color = Color.FromHex("FECD57");
}
else
{
bmiLevel = "Obese"; color = Color.FromHex("EC5564");
}
lblBMI.Text = bmiLevel;
bmiStack.BackgroundColor = color;
}

If a user does not enter anything in the entry, the Text of entry is Empty("");
If a user does not select anything in the picker, the SelectedItem of picker is null;
And in your CalculateBMI function, you should first validate 3 values and then calculate BMI:
void CalculateBMI(object sender, EventArgs e)
{
if ((string.IsNullOrEmpty(peso.Text)) || (Pies.SelectedItem == null) || (Pulgadas.SelectedItem == null))
{
DisplayAlert("Attention", "Please complete all the data.", "Ok");
return;
}
double weight = Double.Parse(peso.Text);
double feets = Double.Parse(Pies.SelectedItem.ToString());
double inches = Double.Parse(Pulgadas.SelectedItem.ToString());
double totalInches = (feets * 12) + inches;
double bmi = (weight * 703) / (totalInches * totalInches);
lblBMIValue.Text = String.Format("Your BMI is {0:0.00}", bmi);
string bmiLevel = "";
Color color = Color.Transparent;
lblBMI.TextColor = Color.White;
if (bmi < 18.5)
{
bmiLevel = "Underweight"; color = Color.FromHex("FECD57");
}
else if (bmi < 25)
{
bmiLevel = "Normal"; color = Color.FromHex("1287CE");
}
else if (bmi < 30)
{
bmiLevel = "Overweight"; color = Color.FromHex("FECD57");
}
else
{
bmiLevel = "Obese"; color = Color.FromHex("EC5564");
}
lblBMI.Text = bmiLevel;
}

bool error = false;
if (string.IsNullOrEmpty(peso.Text) ||
Pies.SelectedItem == null ||
Pulgadas.SelectedItem == null)
{
error = true;
// display error message
}

Related

RangeError (index): Invalid value: Not in inclusive range 0..13: 14 Flutter

Someone to help me? I'm a beginner. I'm trying to get the controller numbers from a textfield. For this I tried to convert the characters to int. Note: in the textfield the user will enter numbers up to three digits
This error appears: RangeError (index): Invalid value: Not in inclusive range 0..13: 14
validate(textController)
{
List textCode = List();
List messageInCode = List();
int validateRepeticions;
var stringText = textController;
for (var b = 0; b < stringText.length; b++)
{
textCode.insert(b, stringText[b]);
}
validateRepeticions = textCode.length;
print(validateRepeticions);
int g = 0;
int k = 0;
do
{
bool comma = true;
List tryToParseInt = List();
int d = 0;// 'd' is responsible for identifying the positional value of a digit
int a = 1;// 'a' increment values to k
int c = 0;// 'c' defines the positions used in tryToParseInt
int completeNumber;
tryToParseInt.insert(c, int.tryParse(textCode[k]));
if (tryToParseInt[c] == null)
{
validateRepeticions--;
}
else
{
d++;
c++;
do
{
tryToParseInt.insert(c, int.tryParse(textCode[k+a]));
if (tryToParseInt[c] == null)
{
completeNumber = tryToParseInt[0];
messageInCode.insert(g, completeNumber);
g++;
comma = false;
validateRepeticions -= 2;
}
else
{
d++;
a++;
c++;
tryToParseInt.insert(c, int.tryParse(textCode[k+a]));
if (tryToParseInt[c] == null)
{
completeNumber = tryToParseInt[0]*10 + tryToParseInt[1];
messageInCode.add(completeNumber);
g++;
comma = false;
validateRepeticions -= 3;
d++;
}
else
{
d++;
completeNumber = tryToParseInt[0]*100 + tryToParseInt[1]*10 + tryToParseInt[2];
messageInCode.add(completeNumber);
g++;
comma = false;
validateRepeticions -= 3;
}
}
} while (comma);
}
d++;
k += d;
} while (validateRepeticions >= 0);
}
Updated code
validate(textEditingController) {
int validateRepeticions = textEditingController.text.length;
List textString = textEditingController.text.split('');
List messageInCode = List();
int k = 0;
do {
bool comma = true;
List tryToParseInt = List();
int d = 0; // 'd' is responsible for identifying the value of a number that has already been verified
int a = 1; // 'a' increment values to k
int c = 0; // 'c' defines the positions used in tryToParseInt
int completeNumber;
tryToParseInt.insert(c, int.tryParse(textString[k]));
if (tryToParseInt[c] == null) {
validateRepeticions--;
} else {
d++; //1
c++; //1
do {
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 2;
} else {
d++; //2
a++; //2
c++; //2
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0] * 10 + tryToParseInt[1];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
d++;
} else {
d++;
completeNumber = tryToParseInt[0] * 100 + tryToParseInt[1] * 10 + tryToParseInt[2];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
}
}
} while (comma);
}
d++;
k += d;
} while (validateRepeticions > 0);
}
Now it's almost working, although an error still appears:
The method '_addFromInteger' was called on null.
Receiver: null
Tried calling: _addFromInteger(0)
validate(textEditingController) {
int validateRepeticions = textEditingController.text.length;
List textString = textEditingController.text.split('');
List messageInCode = List();
int k = 0;
messageInCode.clear();
do {
bool comma = true;
List tryToParseInt = List();
int d = 0; // 'd' is responsible for identifying the positional value of a digit
int a = 0; // 'a' increment values to k
int c = 0; // 'c' defines the positions used in tryToParseInt
int completeNumber;
if (k < textEditingController.text.length) {
tryToParseInt.insert(c, int.tryParse(textString[k]));
if (tryToParseInt[c] == null) {
validateRepeticions--;
} else {
d++; //1 these comments are examples
c++; //1
a++; //1
do {
if ((k + a) < textEditingController.text.length) {
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 2;
} else {
d++; //2
a++; //2
c++; //2
if ((k + a) < textEditingController.text.length) {
tryToParseInt.insert(c, int.tryParse(textString[k + a]));
if (tryToParseInt[c] == null) {
completeNumber = tryToParseInt[0] * 10 + tryToParseInt[1];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
d++;
} else {
d++;
completeNumber = tryToParseInt[0] * 100 + tryToParseInt[1] * 10 + tryToParseInt[2];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
}
} else {
completeNumber = tryToParseInt[0] * 10 + tryToParseInt[1];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 3;
d++;
}
}
} else {
completeNumber = tryToParseInt[0];
messageInCode.add(completeNumber);
comma = false;
validateRepeticions -= 2;
}
} while (comma);
}
} else {
validateRepeticions--;
}
d++;
k += d;
} while (validateRepeticions > 0 && k < textEditingController.text.length);
}
In your function, I'm assuming the param textController is the TextEditingController. In that case you need to check the length with textController.text.length
To create a list of characters from the string, you just need to use split() instead of creating a new list and loop through the string. For example: textController.text.split('')
Replace textCode.insert(b, stringText[b]); with textCode.add(stringText[b]);

Check if Edittext is empty that only accepts numbers

I have 2 Edittext which only accepts numbers.
I want to make sure that the fields are not empty before the submit button is pressed to stop the application from crashing.
These are the 2 edittext fields i have.
EditText weightText = (EditText)findViewById(R.id.WeightText);
EditText heightText = (EditText)findViewById(R.id.Heighttext);
Code:
public class BMI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
}
public void calculateHandler(View view) {
// make sure we handle the click of the calculator button
if (view.getId() == R.id.calculate) {
// get the references to the widgets
EditText weightText = (EditText)findViewById(R.id.WeightText);
EditText heightText = (EditText)findViewById(R.id.Heighttext);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
}
}
private float calculateBMI (float weight, float height) {
return (float)Math.round((weight / (height * height)) * 100) / 100 ;
}
// interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}
You can check that your EditTexts are not empty like below:
weightText.getText().length() != 0 && heightText.getText().length() != 0
And you can use this condition inside the onClick(View) method, which is called when your button is clicked like below:
yourButton.setOnClickListener( new OnClickListener(){
public void onClick(){
if(weightText.getText().length() != 0 && heightText.getText().length() != 0){
//do sth
}
});
The second way, you can create TextWatcher which set to both EditTexts and in onTextChanged() you can check that both EditTexts are not empty like below:
private class YourTextWatcher implements TextWatcher{
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
yourButton.setEnabled(weightText.getText().length() != 0 && heightText.getText().length() != 0)
}
#Override
public void afterTextChanged(Editable editable) {
}
}
you can set this TextWatcher for your EditText like below:
weightText.addTextChangedListener(new YourTextWatcher());
heightText.addTextChangedListener(new YourTextWatcher());
Here is code that your Activity should look like:
public class BMI extends Activity {
EditText weightText;
EditText heightText;
TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
weightText = (EditText) findViewById(R.id.WeightText);
heightText = (EditText) findViewById(R.id.Heighttext);
resultText = (TextView) findViewById(R.id.resultLabel);
Button button = (Button) findViewById(R.id.calulate);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculateHandler();
}
});
}
public void calculateHandler() {
// make sure we handle the click of the calculator button
if (weightText.getText().length() == 0 || heightText.getText().length() == 0) {
return;
}
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
// display toast additionally to example
Toast.makeText(this, bmiValue + " = " + bmiInterpretation, Toast.LENGTH_LONG).show();
}
private float calculateBMI(float weight, float height) {
return (float) Math.round((weight / (height * height)) * 100) / 100;
}
// interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}
Calculate method
public void calculateHandler() {
// make sure we handle the click of the calculator button
if (weightText.getText().toString().trim().length() == 0 || heightText.getText().toString().trim().length() == 0) {
Toast.makeText(this, "Please fill all field by numbers", Toast.LENGTH_LONG).show();
return;
}
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
// display toast additionally to example
}
weightText.getText().toString().isEmpty();
try like this..
String weight = weightText.getText().toString();
String height = heightText.getText().toString();
if((Integer.parseInt(weight)!=null) && (Integer.parseInt(height)!=null)){
//Not an empty
}
else{
//empty
}

I am using unity3D engine to create a game involving cars

while doing the controls I have encountered the following errors.
Assets/Car/Scripts/NewBehaviourScript.js(78,22): UCE0001: ';' expected. Insert a semicolon at the end.
Assets/Car/Scripts/NewBehaviourScript.js(78,10): BCE0044: expecting (, found 'ShiftGears'.
Assets/Car/Scripts/NewBehaviourScript.js(79,9): BCE0043: Unexpected token: if.
Assets/Car/Scripts/NewBehaviourScript.js(79,41): UCE0001: ';' expected. Insert a semicolon at the end.
these errors does'nt usually appear in sxripting in unity and this is the first time that I have encountered it.
here is my code
#pragma strict
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var BackLeftWheel : WheelCollider;
var BackRightWheel : WheelCollider;
var gasButton : GUITexture;
var breakButton : GUITexture;
var leftTurnButton : GUITexture;
var rightTurnButton : GUITexture;
var motorInputTouch : int = 0;
var breakPower : float = 200;
var GearRatio : float[];
var CurrentGear : int = 0;
var EngineTorque : float = 230.0;
var MaxEngineRPM : float = 3000.0;
var MinEngineRPM : float = 1000.0;
private var EngineRPM : float = 0.0;
function Awake() {
gasButton = GameObject.Find("Gas_Pedal").guiTexture;
breakButton = GameObject.Find("brake_Pedal").guiTexture;
leftTurnButton = GameObject.Find("Left_Turn_Button").guiTexture;
rightTurnButton = GameObject.Find("Right_Turn_Button").guiTexture;
}
function start() {
rigidbody.centerOfMass += Vector3(0, -1, .25);
}
function update() {
for (var touch : Touch in Input.touches)
{
if (touch.phase == TouchPhase.Stationary && gasButton.HitTest (touch.position)){
motorInputTouch = 1;
}
else if (touch.phase == TouchPhase.Ended && gasButton.HitTest){
motorInputTouch = 0;
}
if (touch.phase == TouchPhase.Stationary && breakButton.HitTest (touch.position)){
breakPower = 200;
}
else if (touch.phase == TouchPhase.Ended && breakButton.HitTest){
breakPower = 0;
}
if (touch.phase == TouchPhase.Stationary && leftTurnButton.HitTest (touch.position)){
FrontLeftWheel.steerAngle = -15;
FrontRightWheel.steerAngle = -15;
}
else if (touch.phase == TouchPhase.Ended && leftTurnButton.HitTest){
FrontLeftWheel.steerAngle = 0;
FrontRightWheel.steerAngle = 0;
}
if (touch.phase == TouchPhase.Stationary && rightTurnButton.HitTest (touch.position)){
FrontLeftWheel.steerAngle = 15;
FrontRightWheel.steerAngle = 15;
}
else if (touch.phase == TouchPhase.Ended && rightTurnButton.HitTest){
FrontLeftWheel.steerAngle = 0;
FrontRightWheel.steerAngle = 0;
}
EngineRPM = (FrontLeftWheel.rpm + FrontRightWheel.rpm)/2 * GearRatio[CurrentGear];
ShiftGears();
audio.pitch = Mathf.Aba(EngineRPM / MaxEngine + 1.0);
if (audio.pitch > 2.0) {
audio.pitch = 2.0;
}
FrontLeftWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * motorInputTouch;
FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear] * motorInputTouch;
//FrontLeftWheel.steerAngle = 10 * Input.GetAxis("Horizontal");
//FrontRightWheel.steerAngle = 10 * Input.GetAxis("Horizontal");
}
function ShiftGears() {
if ( EngineRPM >= MaxEngineRPM ) {
var AppropriateGear : int = CurrentGear;
for ( var i = 0; i < GearRatio.length; i++) {
if (FrontLeftWheel.rpm * GearRatio[i] < MaxEngineRPM ) {
AppropriateGear = i;
break;
}
}
CurrentGear = AppropriateGear;
}
if (EngineRPM <= MinEngineRPM ) {
AppropriateGear = CurrentGear;
for (var j = GearRatio.Length-1; j >= 0; j--) {
if ( FrontLeftWheel.rpm * GearRatio[j] > MinEngineRPM ) {
AppropriateGear = j;
break;
}
}
CurrentGear = AppropriateGear;
}
}
any one here who can help me debug this? thanks a lot.
You are missing a closing bracket }. Either to end your for loop inside the Update(), or to signify the end of your Update() function. That causes the rest of the errors you're seeing.

Libgdx: Character movement and animation

Good day dear sirs. I have encountered a problem with the animation and controls of my character. My problem is whenever I tried to press the left and right arrow key my player moves up and down instead of going left and right. I did tried to debug my code by I still can't find out which part of the code is wrong. That's why I'm asking you guys to look up my code and could possibly tell which part of the code is wrong or needs improvement.
This is my code for my player:
public class DugmanPlayer {
public enum state
{
standby,
walking,
digging,
dying
}
public enum dir
{
left,
right,
up,
down
}
public static float WIDTH;
public static float HEIGHT;
static float speedmax = 30f;
static float damping = 0.9f;
dir d = dir.up;
public Vector2 position = new Vector2();
public Vector2 speed = new Vector2();
state st = state.walking;
public float statetime = 0;
public void UpdatePlayer(float deltatime)
{
if(deltatime==0)return;
statetime += deltatime;
//rightwalking
if(Math.abs(speed.x) > speedmax) {
speed.x = Math.signum(speed.x) * speedmax;
if(d != dir.left)d = dir.right;
st = state.walking;
}
if(Math.abs(speed.x) < 1) {
speed.x = 0;
if(st!=state.walking)st = state.standby;
d=dir.right;
}
//upwalking
if(Math.abs(speed.y) > speedmax) {
speed.y = Math.signum(speed.y) * speedmax;
if(d != dir.down)d = dir.up;
st = state.walking;
}
if(Math.abs(speed.y) < 1) {
speed.y = 0;
if(st != state.walking)st = state.standby;
d=dir.up;
}
if(Math.abs(-speed.x)>speedmax)
{
speed.x = Math.signum(-speed.x) * speedmax;
if(d != dir.right)d = dir.left;
st = state.walking;
}
if(Math.abs(-speed.x)<1)
{
speed.x = 0;
if(st!=state.walking)st = state.standby;
d=dir.up;
}
if(Math.abs(-speed.y)>speedmax){
speed.y = Math.signum(-speed.y) * speedmax;
if(d != dir.up)d = dir.down;
st = state.walking;
}
if(Math.abs(-speed.y)<1)
{
speed.y = 0;
if(st!=state.walking)st = state.standby;
d=dir.down;
}
speed.scl(deltatime);
position.add(speed);
speed.scl(1/deltatime);
// Apply damping to the velocity on the x-axis so we don't
// walk infinitely once a key was pressed
speed.x *= damping;
speed.y *= damping;
InputProcess();
}
TextureRegion left;
TextureRegion right;
TextureRegion up;
TextureRegion down;
TextureRegion standby;
Animation Walkingleft;
Animation WalkingRight;
Animation WalkingUp;
Animation WalkingDown;
Animation stndbyleft,stndbyright,stndbyup,stndbydown;
public void LoadPlayerTexture()
{
TextureAtlas dug = new TextureAtlas(Gdx.files.internal("character/walking.pack"));
left = dug.findRegion("faceleft");
right = dug.findRegion("faceright");
up = dug.findRegion("faceup");
down = dug.findRegion("facedown");
TextureRegion[] leftwalk = left.split(left.getRegionWidth()/3, left.getRegionHeight()/1)[0];
TextureRegion[] rightwalk = right.split(right.getRegionWidth()/3, right.getRegionHeight()/1)[0];
TextureRegion[] upwalk = up.split(up.getRegionWidth()/3, up.getRegionHeight()/1)[0];
TextureRegion[] downwalk = down.split(down.getRegionWidth()/3, down.getRegionHeight()/1)[0];
Walkingleft = new Animation(0.5f, leftwalk[0],leftwalk[1],leftwalk[2]);
WalkingRight = new Animation(0.5f, rightwalk[0],rightwalk[1],rightwalk[2]);
WalkingUp = new Animation(0.5f, upwalk[0],upwalk[1],upwalk[2]);
WalkingDown = new Animation(0.5f, downwalk[0],downwalk[1],downwalk[2]);
stndbyleft = new Animation(0, leftwalk[1]);
stndbyright = new Animation(0, rightwalk[1]);
stndbyup = new Animation(0, upwalk[1]);
stndbydown = new Animation(0, downwalk[1]);
DugmanPlayer.WIDTH = 1/16f * leftwalk[0].getRegionWidth();
DugmanPlayer.HEIGHT = 1/16f * leftwalk[0].getRegionHeight();
}
public void DrawPlayer(float deltatime, OrthogonalTiledMapRenderer r)
{
Animation fm = null;
boolean loop = true;
switch (st) {
case standby: if(speed.y == 0){
fm = stndbyup;
}
else if(-speed.y == 0){
fm = stndbydown;
}else if (speed.x == 0) {
fm = stndbyright;
}else if (-speed.x == 0) {
fm = stndbyleft;
}
break;
case walking: if(speed.y>speedmax){
fm = WalkingUp;
}else if(-speed.y>speedmax){
fm = WalkingDown;
}else if (speed.x>speedmax) {
fm = WalkingRight;
}else if (-speed.x>speedmax) {
fm = Walkingleft;
}
break;
case digging:
break;
case dying:
break;
default:
break;
}
SpriteBatch batch = r.getSpriteBatch();
batch.begin();
batch.draw(fm.getKeyFrame(statetime, loop), position.x, position.y, WIDTH, HEIGHT);
batch.end();
}
public void InputProcess()
{
if(Gdx.input.isKeyPressed(Keys.UP) || Gdx.input.isKeyPressed(Keys.W)) {
if(st != state.standby)st = state.walking;
speed.y += speedmax;
d = dir.up;
}
else if(Gdx.input.isKeyPressed(Keys.DOWN) || Gdx.input.isKeyPressed(Keys.S)) {
if(st!=state.standby)st = state.walking;
speed.y = -speedmax;
d = dir.down;
}
else if(Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A)) {
if(st!=state.standby)st = state.walking;
speed.y = -speedmax;
d = dir.left;
}
else if(Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D)) {
if(st!=state.standby)st = state.walking;
speed.y += speedmax;
d = dir.right;
}
else
{
st = state.standby;
speed.x = 0;
speed.y = 0;
}
}
}
What I did with my character class is that it will contain all the inputs for my character, render the animation to specific states and direction.
else if(Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A)) {
if(st!=state.standby)st = state.walking;
speed.y = -speedmax;
d = dir.left;
}
else if(Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D)) {
if(st!=state.standby)st = state.walking;
speed.y += speedmax;
d = dir.right;
}
dont you think that u shuld use speed.x instead of speed.y in this code :)

TextView onTouchEvent within customview

I have a custom view, and within the custom view I create 4 text views. I want each of these text views to respond to on touch events. However, the textviews themselves do not respond to an on touch event. I can however, make an ontouch listener for the entire custom view. However, I do not want the whole view to have an ontouch event because I want the textviews that I have created to be dragged and dropped. I tried going the route of registering the x and y coordinates of the ontouch event and assuming that if the ontouch event is within the bounds of a textview, to change the coordinates of the textview, but that was overly complicated because if one textview got dragged to the coordinates of another one, then the ontouch event would "pick up" the other textview, so then I'd be moving two text views, which is not what I want. So, to sum it up, I want to know if it's possible to set in ontouch listener for a textview inside a customview, and if possible, why it is not working:
mScale.mPositive.get(0).setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScale.mCurrentXPos[0] = event.getX();
mScale.mCurrentYPos[0] = event.getY();
mScale.mDrag = true;
return true;
}
});
This same code works for the custom view, but not for the specific textviews inside that customview.
Here is the custom view code:
public class Scale extends View
{
public Scale(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = this.getContext();
h = new Handler();
mCalendarDbHelper=new CalendarDbAdapter(mContext);
mCalendarDbHelper.open();
Cursor thoughts = mCalendarDbHelper.fetchThoughts();
//create a string array of negative thoughts from the db
while (thoughts.moveToNext())
{
if (thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)).length() > 0 && thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)).charAt(0) == '-')
{
negative_thoughts.add(thoughts.getString(thoughts.getColumnIndexOrThrow(CalendarDbAdapter.COLUMN_NAME_THOUGHT)));
}
}
thoughts.close();
array_size = negative_thoughts.size();
mBag =BitmapFactory.decodeResource(getResources(), R.drawable.bag);
mGreenBag = BitmapFactory.decodeResource(getResources(), R.drawable.green_bag);
for (int i = 0; i < 72; i ++)
{
try
{
mScale[i] = BitmapFactory.decodeStream(context.getAssets().open("scale_"+i+".gif"));
}
catch (IOException e)
{
}
}
}
private Runnable r= new Runnable()
{
#Override
public void run() {
invalidate();
}
};
protected void onDraw (Canvas canvas)
{
if (first == true)
{
width = this.getWidth();
height = this.getHeight();
mScale[i] = Bitmap.createScaledBitmap(mScale[i], (int) (width * 1.5), height, true);
mBag = Bitmap.createScaledBitmap(mBag, width/2, height/2, true);
negative = new TextView(mContext);
word = negative_thoughts.get((int) (Math.random() * array_size));
negative.setText(word);
negative.layout(0, 0, width/3, height/4);
negative.setGravity(Gravity.CENTER);
negative.setTextSize(15);
negative.setTextColor(Color.BLACK);
negative.setTypeface(Typeface.DEFAULT_BOLD);
negative.setShadowLayer(5, 2, 2, Color.WHITE);
negative.setDrawingCacheEnabled(true);
negative.setBackgroundResource(R.drawable.graycloud);
positive_paint.setColor(Color.parseColor("#FF4444"));
positive_paint.setShadowLayer(5, 2, 2, Color.YELLOW);
positive_paint.setTypeface(Typeface.DEFAULT_BOLD);
positive_paint.setTextSize(25);
mCurrentXPos[0] = (width/2);
mCurrentYPos[0] = height/4;
mCurrentXPos[1] = (width/2) + (width/8);
mCurrentYPos[1] = height/6;
mCurrentXPos[2] = width/2;
mCurrentYPos[2] = height/12;
mCurrentXPos[3] = (width/2) + (width/8);
mCurrentYPos[3] = height/18;
mMoveXPos[0] = ((width/2) - width)/FRAME_RATE;
mMoveYPos[0] = ((height/4) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[1] = (((width/2) + (width/8)) - width)/ FRAME_RATE;
mMoveYPos[1] = ((height/6) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[2] = ((width/2) - width)/ FRAME_RATE;
mMoveYPos[2] = ((height/12) - (height + (height/4)))/FRAME_RATE;
mMoveXPos[3] = (((width/2) + (width/8)) - width)/ FRAME_RATE;
mMoveYPos[3] = ((height/18) - (height + (height/4)))/FRAME_RATE;
mMoveByXPos[0] = -(width/2)/ FRAME_RATE;
mMoveByYPos[0] = -(height/4)/FRAME_RATE;
mMoveByXPos[1] = ((width - (width/3)) - (width/2 + (width/8)))/ FRAME_RATE;
mMoveByYPos[1] = -(height/6)/FRAME_RATE;
mMoveByXPos[2] = - (width/2)/ FRAME_RATE;
mMoveByYPos[2] = ((height) - (height/12))/FRAME_RATE;
mMoveByXPos[3] = ((width - (width/3)) - (width/2 + (width/8)))/ FRAME_RATE;
mMoveByYPos[3] = ((height) - (height/18))/FRAME_RATE;
currentX = width;
currentY = height + height/4;
first = false;
}
if (game_over == false)
{
canvas.drawBitmap(mScale[i], 0 - (width/4), 0, null);
canvas.drawBitmap(negative.getDrawingCache(),(int) (width/12), (int) (height - (height)/2.5) - (j), null);
}
else
{
canvas.drawBitmap(mBag, width/4, height/4, null);
}
if (mMoveScale == true)
{
i++;
j+=3;
ScaleIt(canvas, i);
if (i == 21 || i == 37 || i == 53 || i == 71)
{
mMoveScale = false;
}
}
if (tracker > 0)
{
if (tracker == 1)
{
if (currentX > width/2 && currentY > height/4 && sStop == false)
{
currentX += mMoveXPos[0];
currentY += mMoveYPos[0];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 2)
{
if (currentX > width/2 + (width/8) && currentY > (height/6) && sStop == false)
{
currentX += mMoveXPos[1];
currentY += mMoveYPos[1];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 3)
{
if (currentX > width/2 && currentY > height/12 && sStop == false)
{
currentX += mMoveXPos[2];
currentY += mMoveYPos[2];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (tracker == 4)
{
if (currentX > width/2 + (width/8) && currentY > (height/18) && sStop == false)
{
currentX += mMoveXPos[3];
currentY += mMoveYPos[3];
canvas.drawBitmap(mPositive.get(tracker -1 ).getDrawingCache(), currentX, currentY, null);
}
else
{
if (sStop == false)
{
mMoveScale = true;
sStop = true;
game_over = true;
currentX = width;
currentY = height + height/4;
draw_em++;
}
}
}
if (draw_em > 0 && game_over == false)
{
for (int i = 0; i < draw_em; i ++)
{
if (i == 0)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2, height/4 + j, null);
}
if (i == 1)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2 + (width/8), height/6 + j, null);
}
if (i == 2)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2, height/12 + j, null);
}
if (i == 3)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), width/2 + (width/8), height/18 + j, null);
}
}
}
else if (game_over == true)
{
for (int i = 0; i < draw_em; i++)
{
if (i == 0 && mCurrentXPos[0] > 0 && mCurrentYPos[0] > 0 && mDrag == false)
{
mCurrentXPos[0] += mMoveByXPos[0];
mCurrentYPos[0] += mMoveByYPos[0];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[0], mCurrentYPos[0], null);
}
else if (i == 0 && mCurrentXPos[0] <= 0 || mCurrentYPos[0] <= 0 && mDrag == false)
{
canvas.drawBitmap(mPositive.get(0).getDrawingCache(), 0, 0, null);
}
else if (i == 0 && mDrag == true)
{
canvas.drawBitmap(mPositive.get(0).getDrawingCache(), mCurrentXPos[0], mCurrentYPos[0], null);
}
if (i == 1 && mCurrentXPos[1] < (width - (mPositive.get(i).getWidth()/2)) && mCurrentYPos[1] > mPositive.get(i).getHeight()/2)
{
mCurrentXPos[1] += mMoveByXPos[1];
mCurrentYPos[1] += mMoveByYPos[1];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[1], mCurrentYPos[1], null);
}
else if (i == 1 && mCurrentXPos[1] >= (width - (mPositive.get(i).getWidth()/2)) || mCurrentYPos[1] <= mPositive.get(i).getHeight()/2)
{
canvas.drawBitmap(mPositive.get(1).getDrawingCache(), width - (width/3), 0, null);
}
if (i == 2 && mCurrentXPos[2] > (mPositive.get(i).getWidth()/2) && mCurrentYPos[2] < (height - mPositive.get(i).getHeight()/2))
{
mCurrentXPos[2] += mMoveByXPos[2];
mCurrentYPos[2] += mMoveByYPos[2];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[2], mCurrentYPos[2], null);
}
else if (i == 2 && mCurrentXPos[2] <= (mPositive.get(i).getWidth()/2) || mCurrentYPos[2] >= (height - mPositive.get(i).getHeight()/2))
{
canvas.drawBitmap(mPositive.get(2).getDrawingCache(), 0, height - (height/4), null);
}
if (i == 3 && mCurrentXPos[3] < (width - (mPositive.get(i).getWidth()/2)) && mCurrentYPos[3] < (height - mPositive.get(i).getHeight()/2))
{
mCurrentXPos[3] += mMoveByXPos[3];
mCurrentYPos[3] += mMoveByYPos[3];
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), mCurrentXPos[3], mCurrentYPos[3], null);
}
else if (i == 3 && mCurrentXPos[3] >= (width - (mPositive.get(i).getWidth()/2)) || mCurrentYPos[3] >= (height - mPositive.get(i).getHeight()/2))
{
canvas.drawBitmap(mPositive.get(3).getDrawingCache(), width - (width/3), height - (height/4), null);
}
}
}
}
h.postDelayed(r, FRAME_RATE);
}
protected void moveIt(Canvas canvas, int moveX,int moveY, int i)
{
if (i == 0)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 1)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 2)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
if (i == 3)
{
canvas.drawBitmap(mPositive.get(i).getDrawingCache(), moveX, moveY, null);
}
}
protected void moveEm(Canvas canvas, int[]mMovePosX, int[] mMovePosY)
{
for (int i = 0; i < 4; i++)
{
}
}
protected void ScaleIt(Canvas canvas, int i)
{
mScale[i] = Bitmap.createScaledBitmap(mScale[i], (int) (width * 1.5), height, true);
mScale[i-1].recycle();
}
}
And here is the activity:
public class ScaleView extends Activity
{
Context mContext;
Scale mScale;
EditText positive_thought;
Button fire;
TextView pos;
private static Set<String> mPositiveWords;
private static Set<String> mNegativeWords;
int count;
private Pattern four_letter_words = Pattern.compile("not|cant|cnt|can't");
String inputLine;
private String[] inputTokens;
Button question;
Button skip;
public static boolean populatePositiveWords(Context context)
{
mNegativeWords = new HashSet<String>();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open("negative_words.txt")));
String line = reader.readLine();
while (line != null)
{
mNegativeWords.add(line.toLowerCase(Locale.US));
line = reader.readLine();
}
reader.close();
}
catch (IOException exception)
{
return false;
}
return true;
//TODO list of negative words
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getActionBar().hide();
mContext = this;
populatePositiveWords(mContext);
setContentView(R.layout.activity_scale);
mScale = (Scale) findViewById(R.id.anim_view);
mScale.setClickable(true);
positive_thought = (EditText) findViewById(R.id.thoughts);
fire = (Button) findViewById(R.id.scale_it);
skip = (Button) findViewById(R.id.skip);
question = (Button) findViewById(R.id.question);
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(60);
positive_thought.setFilters(FilterArray);
fire.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
//if the button is clicked invalidate the ondraw method and pass in the text of the positive word
inputLine = positive_thought.getText().toString();
inputTokens = inputLine.split(" ");
if (inputLine.isEmpty())
{
Toast.makeText(mContext, "You have to write something!", Toast.LENGTH_SHORT).show();
return;
}
if (inputTokens.length < 3)
{
Toast.makeText(mContext, "At least three words are required.", Toast.LENGTH_SHORT).show();
return;
}
if (four_letter_words.matcher(inputLine).find() == true)
{
Toast.makeText(mContext, "Make an affirmative statement!", Toast.LENGTH_SHORT).show();
return;
}
boolean matchesToken = false;
for (int i = 0; i < inputTokens.length; i++)
{
String token = inputTokens[i];
if (mNegativeWords.contains(token.toLowerCase(Locale.US)))
{
matchesToken = true;
break;
}
}
if (matchesToken == true)
{
Toast.makeText(mContext, "Use positive words!", Toast.LENGTH_SHORT).show();
return;
}
else
{
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(positive_thought.getWindowToken(), 0);
pos = new TextView (mContext);
pos.layout(0, 0, mScale.width/3, mScale.height/4);
pos.setGravity(Gravity.CENTER);
pos.setTextSize(15);
pos.setTextColor(Color.RED);
pos.setTypeface(Typeface.DEFAULT_BOLD);
pos.setShadowLayer(5, 2, 2, Color.YELLOW);
pos.setText(positive_thought.getText().toString());
pos.setDrawingCacheEnabled(true);
pos.setBackgroundResource(R.drawable.whitecloud);
pos.setClickable(true);
mScale.mPositive.add(pos);
mScale.scale_it = true;
count++;
mScale.sStop = false;
mScale.tracker = count;
if (count == 4)
{
((RelativeLayout)question.getParent()).removeView(question);
((RelativeLayout)skip.getParent()).removeView(skip);
mScale.mPositive.get(0).setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
mScale.mCurrentXPos[0] = event.getX();
mScale.mCurrentYPos[0] = event.getY();
mScale.mDrag = true;
return true;
}
});
}
}
positive_thought.setText(null);
}
});
}
}
The reason your TextView cannot receive touch events is that the TextView is drawn on the canvas just as a bitmap, not as a View. An excerpt from your code shown below illustrates this.
protected void onDraw(Canvas canvs)
{
....
negative = new TextView(mContext);
...
canvas.drawBitmap(negative.getDrawingCache(), ...)
To deliver touch events to your TextView, your Scale class should extend not View but ViewGroup and the TextView needs to be added as a subview to Scale class by using ViewGroup.addView() or addViewInLayout(). It is not a simple task to implement a ViewGroup subclass. You may have to implement onInterceptTouchEvent(MotionEvent) depending on your needs.
Android's source code will be of help.
Is your CustomView also sets some TouchListner??
If yes then this might causing issue..Remove TouchListner from CustomView and see if it works..

Categories

Resources