I have this app where when i enter some values in editText of 1st activity i.e ActivityA and then press a Button shows the result in next activity i.e ActivityB. But when i revert back to ActivityA and change some values and press button so that i want another ActivityC to be called, ActivityB only appears.
but if i restart my application and put values required to get ActivityC i will get it. how am i supposed solve this problem?
EDIT :
ActivityA
package com.example.iolcalci;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Selection extends Activity implements OnFocusChangeListener{
private EditText k1_e,k2_e,al_e,alconst_e,dr_e;
TextView k1_m,k2_m;
private float k1,k2,al,al_const,dr,Avg_k,v_k1,v_k2,v_dr;
private Float srkt_rnd,srk2_rnd,holladay_rnd,binkhorst_rnd,IOLPower_srkt,IOLPower_srk2,IOLPower_bink,IOLPower_holl;
private float srkt_rf2,srkt_rf3,srkt_rf4,srkt_rf5,srkt_rf6,srkt_rf7,srkt_rf8,srkt_rf9,srkt_rf10,srkt_rf11,srkt_rf12;
private float holladay_rf2,holladay_rf3,holladay_rf4,holladay_rf5,holladay_rf6,holladay_rf7,holladay_rf8,holladay_rf9,holladay_rf10,holladay_rf11,holladay_rf12;
private float binkhorst_rf2,binkhorst_rf3,binkhorst_rf4,binkhorst_rf5,binkhorst_rf6,binkhorst_rf7,binkhorst_rf8,binkhorst_rf9,binkhorst_rf10,binkhorst_rf11,binkhorst_rf12;
private Spinner spin;
private Button result;
private int spinSelected=-1;
int flag = 0;
String k1_s,k2_s,al_s,al_const_s,dr_s;
TextWatcher k1e,k2e,ale,dre;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selective);
setupUI(findViewById(R.id.form_layout));
spin=(Spinner)findViewById(R.id.formulae);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
spinSelected=pos;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
spinSelected=-1;
}
});
dr_e=(EditText)findViewById(R.id.dr_editText);
k1_e=(EditText)findViewById(R.id.k1_editText);
k2_e=(EditText)findViewById(R.id.K2_editText);
al_e=(EditText)findViewById(R.id.al_editText);
alconst_e=(EditText)findViewById(R.id.al_const_editText);
k1_m=(TextView)findViewById(R.id.k1_metric);
k2_m=(TextView)findViewById(R.id.k2_metric);
dr_e.setText("0.0");
dr_e.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
dr_s=dr_e.getText().toString();
v_dr=Float.valueOf(dr_s);
}
});
al_e.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
al_s = al_e.getText().toString();
int dotPos = -1;
for (int i = 0; i < al_s.length(); i++) {
char c = al_s.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
if(al_s.length()==0){
al_e.setText("0.00");
}else{
al_e.setText(al_s + ".00");
}
} else {
if ( al_s.length() - dotPos == 1 ) {
al_e.setText(al_s + "00");
} else if ( al_s.length() - dotPos == 2 ) {
al_e.setText(al_s + "0");
}
}
}
}
});
k1_e.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String k1_s = k1_e.getText().toString();
int dotPos = -1;
for (int i = 0; i < k1_s.length(); i++) {
char c = k1_s.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
if(k1_s.length()==0){
k1_e.setText("0.00");
}else{
k1_e.setText(k1_s + ".00");
}
} else {
if ( k1_s.length() - dotPos == 1 ) {
k1_e.setText(k1_s + "00");
} else if ( k1_s.length() - dotPos == 2 ) {
k1_e.setText(k1_s + "0");
}
}
}
k1_s=k1_e.getText().toString().trim();
k1_e.setText(String.format(k1_s,"##.00"));
if(k1_s.length()!=0){
k1=Float.parseFloat(k1_s);
v_k1=Float.valueOf(k1);
Log.v("K1",""+v_k1);
if((v_k1>=(float)5.63)&&(v_k1<=(float)11.25)){
k1_m.setText("mm");
Log.v("CHECK1", "success1" +v_k1);
}else if((v_k1>=(float)30)&&(v_k1<=(float)60)){
k1_m.setText("D");
Log.v("CHECK1", "success1" +v_k1);
}else{
}
}
}
});
k2_e.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String k2_s = k2_e.getText().toString();
int dotPos = -1;
for (int i = 0; i < k2_s.length(); i++) {
char c = k2_s.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
if(k2_s.length()==0){
k2_e.setText("0.00");
}else{
k2_e.setText(k2_s + ".00");
}
} else {
if ( k2_s.length() - dotPos == 1 ) {
k2_e.setText(k2_s + "00");
} else if ( k2_s.length() - dotPos == 2 ) {
k2_e.setText(k2_s + "0");
}
}
}
k2_s=k2_e.getText().toString().trim();
if(k2_s.length()!=0){
k2=Float.parseFloat(k2_s);
v_k2=Float.valueOf(k2);
Log.v("K2",""+v_k2);
if((v_k2>=5.63)&&(v_k2<=11.25)){
k2_m.setText("mm");
Log.v("CHECK2", "success2" +v_k2);
}else if((v_k2>=30)&&(v_k1<=60)){
k2_m.setText("D");
Log.v("CHECK2", "success2" +v_k2);
}else{
}
}
}
});
result=(Button)findViewById(R.id.result);
result.setOnClickListener(new OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(dr_e.getText().toString().length()==0|al_e.getText().toString().length()==0|alconst_e.getText().toString().length()==0){
flag=1;
}else{
dr=Float.parseFloat(dr_e.getText().toString());
al=Float.parseFloat(al_e.getText().toString());
al_const=Float.parseFloat(alconst_e.getText().toString());
k1=Float.parseFloat(k1_e.getText().toString().trim());
k2=Float.parseFloat(k2_e.getText().toString().trim());
}
if((v_k1>=(float)5.63)&&(v_k1<=(float)11.25)){
k1=Round((float)(337.5/v_k1),2);
}
if((v_k2>=(float)5.63)&&(v_k2<=(float)11.25)){
k2=Round((float)(337.5/v_k2),2);
}
Avg_k=(k1+k2)/2;
if(spinSelected==0){
IOLPower_srkt=Srkt();
if(flag!=1){
Intent iSrkt=new Intent(Selection.this,Srkt.class);
iSrkt.putExtra("RESULT", IOLPower_srkt);
iSrkt.putExtra("DR", dr);
iSrkt.putExtra("IOL", srkt_rnd);
iSrkt.putExtra("REFER7", srkt_rf7);
iSrkt.putExtra("REFER2", srkt_rf2);
iSrkt.putExtra("REFER3", srkt_rf3);
iSrkt.putExtra("REFER4", srkt_rf4);
iSrkt.putExtra("REFER5", srkt_rf5);
iSrkt.putExtra("REFER6", srkt_rf6);
iSrkt.putExtra("REFER8", srkt_rf8);
iSrkt.putExtra("REFER9", srkt_rf9);
iSrkt.putExtra("REFER10", srkt_rf10);
iSrkt.putExtra("REFER11", srkt_rf11);
iSrkt.putExtra("REFER12", srkt_rf12);
startActivity(iSrkt);
}else{
Intent iSrktx=new Intent(Selection.this,Srkt_x.class);
startActivity(iSrktx);
}
}else if(spinSelected==1){
IOLPower_bink=Binkhorst();
if(flag!=1){
Intent iBinkhorst=new Intent(Selection.this,Binkhorst.class);
iBinkhorst.putExtra("RESULT", IOLPower_bink);
iBinkhorst.putExtra("DR", dr);
iBinkhorst.putExtra("IOL", binkhorst_rnd);
iBinkhorst.putExtra("REFER7", binkhorst_rf7);
iBinkhorst.putExtra("REFER2", binkhorst_rf2);
iBinkhorst.putExtra("REFER3", binkhorst_rf3);
iBinkhorst.putExtra("REFER4", binkhorst_rf4);
iBinkhorst.putExtra("REFER5", binkhorst_rf5);
iBinkhorst.putExtra("REFER6", binkhorst_rf6);
iBinkhorst.putExtra("REFER8", binkhorst_rf8);
iBinkhorst.putExtra("REFER9", binkhorst_rf9);
iBinkhorst.putExtra("REFER10", binkhorst_rf10);
iBinkhorst.putExtra("REFER11", binkhorst_rf11);
iBinkhorst.putExtra("REFER12", binkhorst_rf12);
startActivity(iBinkhorst);
}else{
Intent iBinkhorstx=new Intent(Selection.this,Binkhorst_x.class);
startActivity(iBinkhorstx);
}
}else if(spinSelected==2){
IOLPower_srk2=Srk2();
if((Math.ceil(IOLPower_srk2)-IOLPower_srk2)>0.5){
srk2_rnd=(float) Math.floor(IOLPower_srk2);
}else{
srk2_rnd=(float) Math.ceil(IOLPower_srk2);
}
if(flag!=1){
Intent iSrk2=new Intent(Selection.this,Srk2.class);
iSrk2.putExtra("RESULT", IOLPower_srk2);
iSrk2.putExtra("DR", dr);
iSrk2.putExtra("IOL", srk2_rnd);
startActivity(iSrk2);
}else{
Intent iSrk2x=new Intent(Selection.this,Srk2_x.class);
startActivity(iSrk2x);
}
}else{
IOLPower_holl=Holladay();
if(flag!=1){
Intent iHolladay=new Intent(Selection.this,Holladay.class);
iHolladay.putExtra("RESULT", IOLPower_holl);
iHolladay.putExtra("DR", dr);
iHolladay.putExtra("IOL", holladay_rnd);
iHolladay.putExtra("REFER7", holladay_rf7);
iHolladay.putExtra("REFER2", holladay_rf2);
iHolladay.putExtra("REFER3", holladay_rf3);
iHolladay.putExtra("REFER4", holladay_rf4);
iHolladay.putExtra("REFER5", holladay_rf5);
iHolladay.putExtra("REFER6", holladay_rf6);
iHolladay.putExtra("REFER8", holladay_rf8);
iHolladay.putExtra("REFER9", holladay_rf9);
iHolladay.putExtra("REFER10", holladay_rf10);
iHolladay.putExtra("REFER11", holladay_rf11);
iHolladay.putExtra("REFER12", holladay_rf12);
startActivity(iHolladay);
}else{
Intent iHolladayx=new Intent(Selection.this,Holladay_x.class);
startActivity(iHolladayx);
}
}
}
});
Button reset=(Button) findViewById(R.id.reset);
reset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dr_e.setText("0.0");
al_e.setText("");
k1_e.setText("");
k2_e.setText("");
alconst_e.setText("");
dr_e.requestFocus();
}
});
}
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
public float Srkt(){
float Rcor;
float Lcor;
float Crwdest;
float Corneal_H;
float Acd_Const;
float Offset;
float Acd_Est;
float Na=(float) 1.336;
float C2=(float) 0.3333;
float C3;
float C4;
float C5;
float C6;
float C8;
float C9;
float Iolam;
float Rcor1=(float)(337.5/Avg_k);Rcor=Round(Rcor1,2);
if(al<=24.2){
Lcor=al;
}else{
Lcor=(float) (-3.446+1.716*al-0.0237*(al*al));
}Lcor=Round(Lcor,2);
Crwdest=(float) (-5.41+0.58412*Lcor+0.098*Avg_k);Crwdest=Round(Crwdest,2);
Corneal_H=(float) (Rcor-(Math.sqrt(Rcor*Rcor-Crwdest*Crwdest/4)));Corneal_H=Round(Corneal_H,2);
Acd_Const=(float) (0.62467*al_const-68.747);
Offset=(float) (Acd_Const-3.336);Offset=Round(Offset,2);
Acd_Est=(Corneal_H+Offset); float Acd_Est1=Round(Acd_Est,2);
C3=(float) (0.97971*al+0.65696);C3=Round(C3,2);
C4=C3-Acd_Est1;C4=Round(C4,2);
C5=(float) ((Na*Rcor)-(C2*Acd_Est)); C5=Round(C5, 2);
C6=(float) ((Na*Rcor1)-(C2*C3));
C8=(float) ((12*C6)+(C3*Rcor1));C8=Round(C8,2);
C9=(float) ((12*C5)+(Acd_Est*Rcor1));C9=Round(C9,2);
Iolam=(float) ((1336*(C6-(0.001*C8*dr)))/(C4*(C5-(0.001*dr*C9))));Iolam=Round(Iolam,2);
if((Math.ceil(Iolam)-Iolam)>0.5){
srkt_rnd=(float) Math.floor(Iolam);
}else{
srkt_rnd=(float) Math.ceil(Iolam);
}
srkt_rf7=(float) (((1336*C6)-(srkt_rnd*C4*C5))/((1.336*C8)-(0.001*srkt_rnd*C4*C9)));
srkt_rf6=(float) (((1336*C6)-((srkt_rnd+0.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+0.5)*C4*C9)));
srkt_rf5=(float) (((1336*C6)-((srkt_rnd+1)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+1)*C4*C9)));
srkt_rf4=(float) (((1336*C6)-((srkt_rnd+1.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+1.5)*C4*C9)));
srkt_rf3=(float) (((1336*C6)-((srkt_rnd+2)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+2)*C4*C9)));
srkt_rf2=(float) (((1336*C6)-((srkt_rnd+2.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+2.5)*C4*C9)));
srkt_rf8=(float) (((1336*C6)-((srkt_rnd-0.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-0.5)*C4*C9)));
srkt_rf9=(float) (((1336*C6)-((srkt_rnd-1)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-1)*C4*C9)));
srkt_rf10=(float) (((1336*C6)-((srkt_rnd-1.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-1.5)*C4*C9)));
srkt_rf11=(float) (((1336*C6)-((srkt_rnd-2)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-2)*C4*C9)));
srkt_rf12=(float) (((1336*C6)-((srkt_rnd-2.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-2.5)*C4*C9)));
return(Iolam);
}
public float Binkhorst(){
float K1;
float LB2;
float ACDbnk;
float xb;
float yb;
float em;
K1=(float)(337.5/Avg_k);
LB2=(float) (al+0.1984);
if(LB2>=26){
ACDbnk=(float) (((0.58357*al_const)-63.896)*1.1087);
}else{
ACDbnk=(float) (((0.58357*al_const)-63.896)*LB2/23.45);
}
xb=(float) (1336*((1.336*K1-0.3333*LB2)-0.001*dr*(16.032*K1-4*LB2+LB2*K1)));
yb=(float) ((LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk-0.001*dr*(16.032*K1-4*ACDbnk+ACDbnk*K1)));
em=xb/yb;em=Round(em,2);
if((Math.ceil(em)-em)>0.5){
binkhorst_rnd=(float) Math.floor(em);
}else{
binkhorst_rnd=(float) Math.ceil(em);
}
binkhorst_rf7=(float) ((1336*((1.336*K1-0.3333*LB2))-binkhorst_rnd*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*binkhorst_rnd*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf6=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+0.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+0.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf5=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+1)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+1)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf4=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+1.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+1.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf3=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+2)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+2)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf2=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+2.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+2.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf8=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-0.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-0.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf9=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-1)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-1)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf10=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-1.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-1.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf11=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-2)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-2)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf12=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-2.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-2.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
return(em);
}
public float Srk2(){
float X25 = 0;
float Avg_k=(k1+k2)/2;
if(al<20.0){
X25=al_const+3;
}else if((al>=20.0)&&(al<21.0)){
X25=al_const+2;
}else if((al>=21.0)&&(al<22.0)){
X25=al_const+1;
}else if((al>=22.0)&&(al<24.5)){
X25=al_const;
}else if(al>=24.5){
X25=(float) (al_const-(0.5));
}else{
Toast.makeText(getApplicationContext(), "Please enter valid AL value", Toast.LENGTH_SHORT).show();
}
float SRK2 = (float) (X25-(0.9*Avg_k+2.5*al));
return(SRK2);
}
public float Holladay(){
float K;
float Lhol;
float SF;
float Rag;
float AGx;
float AG;
float ACDH;
float CAhol;
float xh;
float yh;
float K1=(float)(337.5/Avg_k);K=Round(K1,2);
Lhol=(float) (al+0.2);
SF=(float) ((0.5663*al_const)-65.6);
if(K<7){
Rag=7;
}else{
Rag=K;
}
AGx=(float) (al*0.533);
if(AGx>13.5){
AG=(float) 13.5;
}else{
AG=AGx;
}
ACDH=(float) (0.56+Rag-(Math.sqrt(Rag*Rag-AG*AG/4)));
CAhol=ACDH+SF;
xh=(float) (1336*((1.336*K1-0.3333*Lhol)-0.001*dr*(16.032*K1-4*Lhol+Lhol*K1)));
yh=(float) ((Lhol-CAhol)*(1.336*K1-0.3333*CAhol-0.001*dr*(16.032*K1-4*CAhol+CAhol*K1)));
float em=xh/yh;em=Round(em,2);
if((Math.ceil(em)-em)>0.5){
holladay_rnd=(float) Math.floor(em);
}else{
holladay_rnd=(float) Math.ceil(em);
}
holladay_rf7=(float) ((1336*((1.336*K1-0.3333*Lhol))-holladay_rnd*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*holladay_rnd*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf6=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+0.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+0.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf5=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+1)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+1)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf4=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+1.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+1.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf3=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+2)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+2)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf2=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+2.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+2.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf8=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-0.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-0.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf9=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-1)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-1)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf10=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-1.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-1.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf11=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-2.0)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-2)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf12=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-2.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-2.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
return(em);
}
//when the back button is pressed from next activity
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dr_e.requestFocus();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
hideSoftKeyboard(Selection.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
ActivityB
package com.example.iolcalci;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Srk2 extends Activity {
private Float Result,dr,Srk2_rnd7,Srk2_rnd2,Srk2_rnd3,Srk2_rnd4,Srk2_rnd5,Srk2_rnd6,Srk2_rnd8,Srk2_rnd9,Srk2_rnd10,Srk2_rnd11,Srk2_rnd12;
private Float Ref2,Ref3,Ref4,Ref5,Ref6,Ref7,Ref8,Ref9,Ref10,Ref11,Ref12;
private float Rf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_srk2);
Thread srk2=new Thread(){
public void run() {
TextView power=(TextView) findViewById(R.id.srk2_power);
TextView name=(TextView) findViewById(R.id.iolpower);
Result=getIntent().getExtras().getFloat("RESULT");
dr=getIntent().getExtras().getFloat("DR");
if(dr==0){
name.setText("EM :");
}else{
name.setText("AM :");
}
Srk2_rnd7=getIntent().getExtras().getFloat("IOL");
power.setText(String.valueOf(Result));
//some more calculation
}
};
srk2.start();
}
public float refraction(Float ans){
Rf=refer();
return((Result-ans)/Rf);
}
public float refer(){
float Refer;
if(Result>14){
Refer=(float) 1.25;
}else{
Refer=1;
}
return(Refer);
}
}
ActivityC
package com.example.iolcalci;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
#SuppressLint("NewApi")
public class Srk2_x extends Activity
{
Float result;
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_srk2_x);
TextView text = (TextView) findViewById(R.id.srk2_power);
text.setText("INVALID");
}
}
By maintaining visited activity Queue or use Activity stack to track the activity sequence.
As I can see the flag value is controlling which activity to start. I guess you should change flag to default value when you start a new activity, or override onPause method in your activity and change it there.
Related
I use https://github.com/libgdx/box2dlights in my game, But its not working,
I get the following error in eclipse
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/GLTexture;
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/GLTexture;
at box2dLight.LightMap.render(LightMap.java:41)
at box2dLight.RayHandler.render(RayHandler.java:338)
at box2dLight.RayHandler.updateAndRender(RayHandler.java:269)
at com.mygdx.game.box2dTest.render(box2dTest.java:182)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:207)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
my java file is:
package com.mygdx.game;
import box2dLight.PointLight;
import box2dLight.RayHandler;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
public class box2dTest implements Screen, InputProcessor {
MyGdxGame game;
OrthographicCamera camera;
World world;
Box2DDebugRenderer renderer;
float width,height;
FPSLogger logger;
Body circleBody;
RayHandler handler;
private TmxMapLoader maploader;
TiledMap map;
OrthogonalTiledMapRenderer maprenderer;
private Viewport gamePort;
public box2dTest(MyGdxGame game)
{
this.game=game;
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
//gamePort = new StretchViewport(MyGdxGame.V_WIDTH,MyGdxGame.V_HEIGHT,camera);
camera = new OrthographicCamera(600,440);
camera.position.set(0,220,0);
camera.update();
world = new World(new Vector2(0,-49.8f),false);
renderer = new Box2DDebugRenderer();
logger = new FPSLogger();
BodyDef circleDef = new BodyDef();
circleDef.type = BodyType.DynamicBody;
circleDef.position.set(width/2f,height/2f);
circleBody = world.createBody(circleDef);
CircleShape circleShape = new CircleShape();
circleShape.setRadius(13f);
FixtureDef circleFixture = new FixtureDef();
circleFixture.shape = circleShape;
circleFixture.density = 0.3f;
circleFixture.friction = 0.2f;
circleFixture.restitution = 0.0f;
circleBody.createFixture(circleFixture);
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(0,3);
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox((camera.viewportWidth)*2, 3.0f);
groundBody.createFixture(groundBox ,0.03f);
maploader = new TmxMapLoader();
map = maploader.load("f0c.tmx");
maprenderer = new OrthogonalTiledMapRenderer(map);
//-------grounds--------------------------------------------------------------
BodyDef bDef=new BodyDef();
Body body;
PolygonShape shape=new PolygonShape();
FixtureDef fDef = new FixtureDef();
for(MapObject object : map.getLayers().get(1).getObjects().getByType(RectangleMapObject.class))
{
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bDef.type = BodyDef.BodyType.StaticBody;
bDef.position.set(rect.getX() + rect.getWidth()/2,rect.getY() + rect.getHeight()/2);
body = world.createBody(bDef);
shape.setAsBox(rect.getWidth()/2,rect.getHeight()/2);
fDef.shape=shape;
body.createFixture(fDef);
}
//---------------------------END OF GROUNDS-----------------------------
//--------BOX2D LIGHTS-----//
handler = new RayHandler(world);
handler.setCombinedMatrix(camera.combined);
new PointLight(handler, 5000, Color.CYAN, 100,( width/2)-50, (height/2)+15);
}
public void update(float dt)
{
HandleInput(dt);
camera.position.x = circleBody.getPosition().x;
camera.position.y = circleBody.getPosition().y;
camera.update();
maprenderer.setView(camera);
}
public void HandleInput(float dt)
{
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE) && circleBody.getLinearVelocity().y<10 && circleBody.getLinearVelocity().y>-14)
{
circleBody.applyLinearImpulse(new Vector2(0,19009),circleBody.getWorldCenter(), true);
}
if(Gdx.input.isKeyPressed(Input.Keys.A) && circleBody.getLinearVelocity().x<=122 || (Gdx.input.isTouched(0) && (Gdx.input.getX()>0 && Gdx.input.getX()<250)))
{
circleBody.applyLinearImpulse(new Vector2(-190,0),circleBody.getWorldCenter(), true);
}
if(Gdx.input.isKeyPressed(Input.Keys.D) && circleBody.getLinearVelocity().x>=-122 || (Gdx.input.isTouched(0) && (Gdx.input.getX()>550 && Gdx.input.getX()<840)))
{
circleBody.applyLinearImpulse(new Vector2(190,0),circleBody.getWorldCenter(), true);
}
}
#Override
public void render(float delta) {
Gdx.input.setInputProcessor(this);
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
maprenderer.render();
renderer.render(world, camera.combined);
//box2dlights
handler.updateAndRender();
//end
world.step(1/60f, 6, 2);
logger.log();
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void show() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
world.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int X, int Y, int pointer, int button) {
if(X>250 && X<550 && circleBody.getLinearVelocity().y<10 && circleBody.getLinearVelocity().y>-14)
{
circleBody.applyLinearImpulse(new Vector2(0,19009),circleBody.getWorldCenter(), true);
}
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
I believe you have an old version of libGDX. Change gdxVersion field to gdxVersion = "1.7.0"in build.gradle in the root folder of your project.
I want to implement Swipe in ListView like in Samsung Android Phones calling function
I have a list shown in below image :
Now when I swipe right side at some distance of swipe from left i.e 25% distance it just changed background, like call function in Samsung device or like SwipeListView:
need solution for this.
try this code :
main.xml file
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
raw.xml
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:gravity="left"
android:text="ABC"
android:textSize="22sp" />
<LinearLayout
android:id="#+id/delete_lay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#55ff0000"
android:visibility="gone" >
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_menu_delete"
android:visibility="visible" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:gravity="left"
android:text="Deleting..."
android:textColor="#ff0000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.timroes.swipetodismiss.SwipeDismissList;
import de.timroes.swipetodismiss.SwipeDismissList.SwipeDirection;
import de.timroes.swipetodismiss.SwipeDismissList.UndoMode;
import de.timroes.swipetodismiss.SwipeDismissList.Undoable;
public class MainActivity extends Activity {
ArrayList<String> listData;
ListView listView;
ArrayAdapter<String> adapter;
SwipeListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
listData = new ArrayList<String>();
listData.add("item 1");
listData.add("item 2");
listData.add("item 3");
listData.add("item 4");
listData.add("item 5");
listData.add("item 6");
listData.add("item 7");
listData.add("item 8");
listData.add("item 9");
listData.add("item 10");
listData.add("item 11");
listData.add("item 12");
listData.add("item 13");
listData.add("item 14");
listData.add("item 15");
listData.add("item 16");
listData.add("item 17");
listAdapter = new SwipeListAdapter(MainActivity.this);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
SwipeDismissList.OnDismissCallback callback = new SwipeDismissList.OnDismissCallback() {
#Override
public Undoable onDismiss(AbsListView listView, int position) {
View view = (View) listView.getChildAt(0);
view.animate().alpha(1).setDuration(200).translationX(10);
listAdapter.remove(position);
return null;
}
};
UndoMode mode = SwipeDismissList.UndoMode.SINGLE_UNDO;
SwipeDismissList swipeList = new SwipeDismissList(listView, callback,
mode);
swipeList.setSwipeDirection(SwipeDirection.END);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class SwipeListAdapter extends BaseAdapter {
Context mContext;
public SwipeListAdapter(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private void remove(int pos) {
listData.remove(pos);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.raw, null);
}
TextView textView = (TextView) convertView
.findViewById(R.id.name);
textView.setText(listData.get(position));
RelativeLayout layout = (RelativeLayout) convertView
.findViewById(R.id.parentLayout);
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, 50);
layout.setLayoutParams(params);
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
}
SwipeDismissList.java
import static com.nineoldandroids.view.ViewHelper.setAlpha;
import static com.nineoldandroids.view.ViewHelper.setTranslationX;
import static com.nineoldandroids.view.ViewPropertyAnimator.animate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;
public final class SwipeDismissList implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private AbsListView mListView;
private OnDismissCallback mCallback;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private SortedSet<PendingDismissData> mPendingDismisses = new TreeSet<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private boolean mSwiping;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
private float mDensity;
private boolean mSwipeDisabled;
private UndoMode mMode;
private List<Undoable> mUndoActions;
private Handler mHandler;
private PopupWindow mUndoPopup;
private TextView mUndoText;
private Button mUndoButton;
private SwipeDirection mSwipeDirection = SwipeDirection.BOTH;
private int mAutoHideDelay = 5000;
private String mDeleteString = "Item deleted";
private String mDeleteMultipleString = "%d items deleted";
private boolean mTouchBeforeAutoHide = true;
private int mDelayedMsgId;
View frontView;
View backView;
RelativeLayout layout ;
public enum UndoMode {
SINGLE_UNDO,
MULTI_UNDO,
COLLAPSED_UNDO
};
public enum SwipeDirection {
BOTH,
START,
END
}
public interface OnDismissCallback {
Undoable onDismiss(AbsListView listView, int position);
}
public abstract static class Undoable {
public String getTitle() {
return null;
}
public abstract void undo();
public void discard() { }
}
public SwipeDismissList(AbsListView listView, OnDismissCallback callback) {
this(listView, callback, UndoMode.SINGLE_UNDO);
}
public SwipeDismissList(AbsListView listView, OnDismissCallback callback, UndoMode mode) {
if(listView == null) {
throw new IllegalArgumentException("listview must not be null.");
}
mHandler = new HideUndoPopupHandler();
mListView = listView;
mCallback = callback;
mMode = mode;
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = listView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mDensity = mListView.getResources().getDisplayMetrics().density;
// -- Load undo popup --
LayoutInflater inflater = (LayoutInflater) mListView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.undo_popup, null);
mUndoButton = (Button)v.findViewById(R.id.undo);
mUndoButton.setOnClickListener(new UndoHandler());
mUndoButton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// If user tabs "undo" button, reset delay time to remove popup
mDelayedMsgId++;
return false;
}
});
mUndoText = (TextView)v.findViewById(R.id.text);
mUndoPopup = new PopupWindow(v);
mUndoPopup.setAnimationStyle(R.style.fade_animation);
// Get scren width in dp and set width respectively
int xdensity = (int)(mListView.getContext().getResources().getDisplayMetrics().widthPixels / mDensity);
if(xdensity < 300) {
mUndoPopup.setWidth((int)(mDensity * 280));
} else if(xdensity < 350) {
mUndoPopup.setWidth((int)(mDensity * 300));
} else if(xdensity < 500) {
mUndoPopup.setWidth((int)(mDensity * 330));
} else {
mUndoPopup.setWidth((int)(mDensity * 450));
}
mUndoPopup.setHeight((int)(mDensity * 56));
// -- END Load undo popu --
listView.setOnTouchListener(this);
listView.setOnScrollListener(this.makeScrollListener());
switch(mode) {
case SINGLE_UNDO:
mUndoActions = new ArrayList<Undoable>(1);
break;
default:
mUndoActions = new ArrayList<Undoable>(10);
break;
}
}
private void setEnabled(boolean enabled) {
mPaused = !enabled;
}
public void setAutoHideDelay(int delay) {
mAutoHideDelay = delay;
}
public void setSwipeDirection(SwipeDirection direction) {
mSwipeDirection = direction;
}
public void setUndoString(String msg) {
mDeleteString = msg;
}
public void setUndoMultipleString(String msg) {
mDeleteMultipleString = msg;
}
public void setRequireTouchBeforeDismiss(boolean require) {
mTouchBeforeAutoHide = require;
}
public void discardUndo() {
for(Undoable undoable : mUndoActions) {
undoable.discard();
}
mUndoActions.clear();
mUndoPopup.dismiss();
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
};
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (this.mSwipeDisabled) {
return false;
}
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
}
view.onTouchEvent(motionEvent);
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = Math.abs(mVelocityTracker.getXVelocity());
float velocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
&& velocityY < velocityX && mSwiping && isDirectionValid(mVelocityTracker.getXVelocity())
&& deltaX >= mViewWidth * 0.2f) {
dismiss = true;
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
final View downView = frontView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
animate(frontView)
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
animate(frontView)
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
if(backView != null) {
backView.setVisibility(View.GONE);
frontView.setVisibility(View.VISIBLE);
setTranslationX(frontView, 0);
layout = null;
backView = null;
frontView = null;
}
break;
}
case MotionEvent.ACTION_MOVE: {
if(mTouchBeforeAutoHide && mUndoPopup.isShowing()) {
// Send a delayed message to hide popup
mHandler.sendMessageDelayed(mHandler.obtainMessage(mDelayedMsgId),
mAutoHideDelay);
}
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
// Only start swipe in correct direction
if(isDirectionValid(deltaX)) {
if (Math.abs(deltaX) > mSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL
| (motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
}
} else {
mDownX = motionEvent.getRawX();
deltaX = 0;
}
if(layout == null) {
layout = (RelativeLayout) mDownView;
frontView = layout.getChildAt(0);
backView = layout.getChildAt(1);
}
if(deltaX > 50) {
backView.setVisibility(View.VISIBLE);
}
if (mSwiping) {
setTranslationX(frontView, deltaX);
setAlpha(frontView, Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private boolean isDirectionValid(float deltaX) {
int rtlSign = 1;
// On API level 17 and above, check if we are in a Right-To-Left layout
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if(mListView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
rtlSign = -1;
}
}
// Check if swipe has been done in the corret direction
switch(mSwipeDirection) {
default:
case BOTH:
return true;
case START:
return rtlSign * deltaX < 0;
case END:
return rtlSign * deltaX > 0;
}
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
for(PendingDismissData dismiss : mPendingDismisses) {
if(mMode == UndoMode.SINGLE_UNDO) {
for(Undoable undoable : mUndoActions) {
undoable.discard();
}
mUndoActions.clear();
}
Undoable undoable = mCallback.onDismiss(mListView, dismiss.position);
if(undoable != null) {
mUndoActions.add(undoable);
}
mDelayedMsgId++;
}
if(!mUndoActions.isEmpty()) {
changePopupText();
changeButtonLabel();
// Show undo popup
mUndoPopup.showAtLocation(mListView,
Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM,
0, (int)(mDensity * 15));
// Queue the dismiss only if required
if(!mTouchBeforeAutoHide) {
// Send a delayed message to hide popup
mHandler.sendMessageDelayed(mHandler.obtainMessage(mDelayedMsgId),
mAutoHideDelay);
}
}
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
setAlpha(pendingDismiss.view, 1f);
setTranslationX(pendingDismiss.view, 0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
private void changePopupText() {
String msg = "";
if(mUndoActions.size() > 1 && mDeleteMultipleString != null) {
msg = String.format(mDeleteMultipleString, mUndoActions.size());
} else if(mUndoActions.size() >= 1) {
// Set title from single undoable or when no multiple deletion string
// is given
if(mUndoActions.get(mUndoActions.size() - 1).getTitle() != null) {
msg = mUndoActions.get(mUndoActions.size() - 1).getTitle();
} else {
msg = mDeleteString;
}
}
mUndoText.setText(msg);
}
private void changeButtonLabel() {
String msg;
if(mUndoActions.size() > 1 && mMode == UndoMode.COLLAPSED_UNDO) {
msg = mListView.getResources().getString(R.string.undoall);
} else {
msg = mListView.getResources().getString(R.string.undo);
}
mUndoButton.setText(msg);
}
/**
* Takes care of undoing a dismiss. This will be added as a
* {#link View.OnClickListener} to the undo button in the undo popup.
*/
private class UndoHandler implements View.OnClickListener {
public void onClick(View v) {
if(!mUndoActions.isEmpty()) {
switch(mMode) {
case SINGLE_UNDO:
mUndoActions.get(0).undo();
mUndoActions.clear();
break;
case COLLAPSED_UNDO:
Collections.reverse(mUndoActions);
for(Undoable undo : mUndoActions) {
undo.undo();
}
mUndoActions.clear();
break;
case MULTI_UNDO:
mUndoActions.get(mUndoActions.size() - 1).undo();
mUndoActions.remove(mUndoActions.size() - 1);
break;
}
}
// Dismiss dialog or change text
if(mUndoActions.isEmpty()) {
mUndoPopup.dismiss();
} else {
changePopupText();
changeButtonLabel();
}
mDelayedMsgId++;
}
}
/**
* Handler used to hide the undo popup after a special delay.
*/
private class HideUndoPopupHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if(msg.what == mDelayedMsgId) {
// Call discard on any element
for(Undoable undo : mUndoActions) {
undo.discard();
}
mUndoActions.clear();
mUndoPopup.dismiss();
}
}
}
/**
* Enable/disable swipe.
*/
public void setSwipeDisabled(boolean disabled) {
this.mSwipeDisabled = disabled;
}
}
enjoy!
Use a ListView extension such as android-swipelistview.
You may also need to refer to the demo source. Instructions for setting up the demo can be found here.
To make a phone call when the user swipes left, add the below code to the instance of SwipeListView:
src > activities > SwipeListViewExampleActivity.java > onCreate()
swipeListView.setSwipeListViewListener(new BaseSwipeListViewListener() {
#Override
public void onOpened(int position, boolean toRight) {
if(!toRight) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
}
}
});
For swipe right you can set it to dismiss which should be sufficient for what you are trying to achieve.
res > layout > swipe-list-view-activity.xml > SwipeListView
swipe:swipeActionRight="dismiss"
you can use this library https://github.com/timroes/EnhancedListView An Android ListView with enhanced functionality (e.g. Swipe To Dismiss or Undo).
In the 'MainActivity', I create a function about when I shake the device, it will go to the 'CompassActivity'. And it works. And I want to shake it again and want to back to 'MainActivity', but it doesn't work.
Here is the code of the MainActivity
package com.lab.mapme;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageButton;
public class MainActivity extends Activity implements SensorEventListener {
ImageButton _buttonForward = null;
ImageButton _buttonBackward = null;
ImageButton _buttonLeft = null;
ImageButton _buttonRight = null;
boolean _fisMoved = false;
boolean _bisMoved = false;
boolean _lisMoved = false;
boolean _risMoved = false;
boolean _isShaked = false;
long _lastSampleTime = 0;
private SensorManager _sensorManager;
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
handleAccelerometer(event);
}
}
private void handleAccelerometer(SensorEvent event) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
Acceleration_getCompress(x, y, z);
if (_isShaked) {
startActivity(new Intent(getApplicationContext(),
CompassActivity.class));
}
Acceleration_getDirectionForward(y);
if (_fisMoved) {
_buttonForward.setBackgroundColor(Color.YELLOW);
} else {
_buttonForward.setBackgroundColor(Color.TRANSPARENT);
}
Acceleration_getDirectionBackward(y);
if (_bisMoved) {
_buttonBackward.setBackgroundColor(Color.YELLOW);
} else {
_buttonBackward.setBackgroundColor(Color.TRANSPARENT);
}
Acceleration_getDirectionLeft(x);
if (_lisMoved) {
_buttonLeft.setBackgroundColor(Color.YELLOW);
} else {
_buttonLeft.setBackgroundColor(Color.TRANSPARENT);
}
Acceleration_getDirectionRight(x);
if (_risMoved) {
_buttonRight.setBackgroundColor(Color.YELLOW);
} else {
_buttonRight.setBackgroundColor(Color.TRANSPARENT);
}
}
private void Acceleration_getCompress(float x, float y, float z) {
float a = (x * x + y * y + z * z);
float aToGravity = a
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long currentTime = System.currentTimeMillis();
if (aToGravity >= 2) {
if (currentTime - _lastSampleTime < 200) {
// duration too short, ignore slight movement
return;
}
_lastSampleTime = currentTime;
_isShaked = !_isShaked;
}
}
private void Acceleration_getDirectionForward(float y) {
float a = y;
if (a > a + y) {
_fisMoved = !_fisMoved;
}
}
private void Acceleration_getDirectionBackward(float y) {
float a = y;
if (a < a + y) {
_bisMoved = !_bisMoved;
}
}
private void Acceleration_getDirectionLeft(float x) {
float a = x;
if (a < a + x) {
_lisMoved = !_lisMoved;
}
}
private void Acceleration_getDirectionRight(float x) {
float a = x;
if (a > a + x) {
_risMoved = !_risMoved;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
_buttonForward = (ImageButton) findViewById(R.id.buttonforward);
_buttonBackward = (ImageButton) findViewById(R.id.buttonbackward);
_buttonLeft = (ImageButton) findViewById(R.id.buttonleft);
_buttonRight = (ImageButton) findViewById(R.id.buttonright);
}
#Override
protected void onResume() {
super.onResume();
_sensorManager.registerListener(this,
_sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
_sensorManager.unregisterListener(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;
}
}
ANd it is the code for the CompassActivity
package com.lab.mapme;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.Toast;
public class CompassActivity extends Activity {
private SensorManager _sensorManager;
private Sensor _sensor;
private CompassView _compassView;
boolean _isShaked = false;
long _lastSampleTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
_sensor = _sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
_compassView = new CompassView(this);
setContentView(_compassView);
}
private SensorEventListener _sensorEventListener = new SensorEventListener() {
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// angle between the magnetic north direction
// 0=North, 90=East, 180=South, 270=West
float azimuth = event.values[0];
_compassView.updateData(azimuth);
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
handleAccelerometer(event);
}
}
};
private void handleAccelerometer(SensorEvent event) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
Acceleration_getDirection(x, y, z);
if (_isShaked) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
}
private void Acceleration_getDirection(float x, float y, float z) {
float a = (x * x + y * y + z * z);
float aToGravity = a
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long currentTime = System.currentTimeMillis();
if (aToGravity >= 2) {
if (currentTime - _lastSampleTime < 200) {
// duration too short, ignore slight movement
return;
}
_lastSampleTime = currentTime;
_isShaked = !_isShaked;
}
}
#Override
protected void onResume() {
super.onResume();
if (_sensor != null) {
_sensorManager.registerListener(_sensorEventListener, _sensor,
SensorManager.SENSOR_DELAY_NORMAL);
} else {
Toast.makeText(this, "ORIENTATION Sensor not found",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
if (_sensor != null) {
_sensorManager.unregisterListener(_sensorEventListener);
}
}
}
Using startActivity(new Intent(getApplicationContext(), MainActivity.class)); will create a new activity instance - instead recycle your old activity by calling the onFinish() or onBackPressed() methods in place.
If that doesn't work ensure handleAccelerometer is being called when you shake your device during your CompassActivity.
In my application in Activity I want to set EditText as I click inside(focus) EditText and type a key clear button should appear on right side of EditText and when EditText is empty that clear button have to removed.But it is not showing to me..Which event should I have to implement here..?onTouch or onFocusChange or addTextChangedListener and also what code be there..? following code I have done in activity...
in Activity :
clear = getResources().getDrawable(R.drawable.round_clear);
clear.setBounds(0, 0, clear.getIntrinsicWidth(), clear.getIntrinsicHeight());
and event as
#Override
public void onFocusChange(View v, boolean hasFocus)
{
switch (v.getId())
{
case R.id.uIDEditText:
if(hasFocus && !uIDEditText.getText().toString().isEmpty())
uIDEditText.setCompoundDrawables(null, null, clear, null);
else
uIDEditText.setCompoundDrawables(null, null, null, null);
break;
case R.id.pwdEditText:
if(hasFocus && !pwdEditText.getText().toString().isEmpty())
pwdEditText.setCompoundDrawables(null, null, clear, null);
else
pwdEditText.setCompoundDrawables(null, null, null, null);
break;
}
}
another event is :
#Override
public boolean onTouch(View v, MotionEvent event)
{
switch (v.getId())
{
case R.id.uIDEditText:
final int x = (int)event.getX();
final int y = (int)event.getY();
if(event.getAction() == MotionEvent.ACTION_UP && clear!=null) {
Rect rBounds = clear.getBounds();
int n1 = v.getRight();
int n2 = v.getRight()+rBounds.width();
int n3 = v.getPaddingTop();
int n4 = v.getHeight()-v.getPaddingBottom();
if(x>=(n1) && x<=(n2) && y>=n3 && y<=(n4))
{
uIDEditText.setText("");
event.setAction(MotionEvent.ACTION_CANCEL);
}
}
break;
}
}
I sovled it...created following code
public class CustomEditText extends EditText {
private Drawable dRight;
private Rect rBounds;
CustomEditText(Context context,AttributeSet attributeSet){
super(context,attributeSet);
}
#Override
public void setCompoundDrawables(Drawable left, Drawable top,
Drawable right, Drawable bottom) {
/*if (left != null) {
dLeft = left;
}*/
if (right != null) {
dRight = right;
}
super.setCompoundDrawables(left, top, right, bottom);
}
#Override
public void addTextChangedListener(TextWatcher watcher) {
super.addTextChangedListener(watcher);
}
#Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
if(this.getText().toString().length()>0)
this.setCompoundDrawablesWithIntrinsicBounds(null, null, dRight, null);
else
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
}
#Override
protected void finalize() throws Throwable {
dRight = null;
rBounds = null;
super.finalize();
}
}
and added in xml:
<com.example.screen.CustomEditText
android:id="#+id/uIDEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableRight="#drawable/round_clear"
android:textColor="#ffffff" />
in Activity (edittext ontouch listener):
uIDEditText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_UP)
return false;
if (event.getX() > uIDEditText.getWidth() - clear.getIntrinsicWidth())
{
uIDEditText.setText("");
event.setAction(MotionEvent.ACTION_CANCEL);
}
return false;
}
});
What you want is here .
Use Textwatcher functionality for edittext.
package com.example.editwatch;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
public class MainActivity extends Activity {
EditText edittext_search;
ImageView imageView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext_search=(EditText)findViewById(R.id.editText1);
imageView1=(ImageView)findViewById(R.id.imageView1);
edittext_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if(edittext_search.getText().length()>0)
{
imageView1.setVisibility(View.VISIBLE);
}
else
{
imageView1.setVisibility(View.GONE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
}
I am making an android game that is checking the players health value when this method is being runned. But however, it's not reacting. It doesn't do anything, when the value is less than 3, it shouldn't do anything, but when it is equal to 3, it should run a method. Please help me and thanks SO much in advance! This is the code that i am using:
private void checkLivesLeftValue() {
if (livesLeftValue == 3) {
//Message to display: "You lost!
onMethod();
}
else {
livesLeftValue = livesLeftValue + 1;
}
}
Full code:
package com.mysoftwaremobileapps.ParachuteHunter;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;
public class ExampleView extends SurfaceView implements SurfaceHolder.Callback
{
class ExampleThread extends Thread
{
private ArrayList<Parachuter> parachuters;
private Bitmap parachuter;
private Paint black;
private boolean running;
private SurfaceHolder mSurfaceHolder;
private Context mContext;
private Handler mHandler;
private GameScreenActivity mActivity;
private long frameRate;
private boolean loading;
public float x;
public float y;
public MediaPlayer mp1;
public int parachuterIndexToResetAndDelete;
public int canvasGetWidth;
public int livesLeftValue;
public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler)
{
mSurfaceHolder = sHolder;
mHandler = handler;
mContext = context;
mActivity = (GameScreenActivity) context;
parachuters = new ArrayList<Parachuter>();
parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman);
black = new Paint();
black.setStyle(Paint.Style.FILL);
black.setColor(Color.WHITE);
running = true;
// This equates to 26 frames per second.
frameRate = (long) (1000 / 26);
loading = true;
}
#Override
public void run()
{
while (running)
{
Canvas c = null;
try
{
c = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder)
{
long start = System.currentTimeMillis();
doDraw(c);
long diff = System.currentTimeMillis() - start;
if (diff < frameRate)
Thread.sleep(frameRate - diff);
}
} catch (InterruptedException e)
{
}
finally
{
if (c != null)
{
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
protected void doDraw(Canvas canvas)
{
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black);
canvasGetWidth = canvas.getWidth();
//Draw
for (int i = 0; i < parachuters.size(); i++)
{
canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null);
parachuters.get(i).tick();
}
//Remove
for (int i = 0; i < parachuters.size(); i++)
{
if (parachuters.get(i).getY() > canvas.getHeight()) {
parachuters.remove(i);
onPlaySound();
checkLivesLeftValue();
}
}
}
public void onPlaySound()
{
try {
mp1 = MediaPlayer.create(getContext(), R.raw.bombsound);
mp1.start();
} catch (Exception e) {
e.printStackTrace();
mp1.release();
}
}
public void onMethod() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "You lost!", 15).show();
}
});
}
private void checkLivesLeftValue() {
// TODO Auto-generated method stub
if (livesLeftValue == 3) {
//Message to display: "You lost!
onMethod();
}
else {
livesLeftValue = livesLeftValue + 1;
}
}
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() != MotionEvent.ACTION_DOWN)
return false;
float x1 = event.getX();
float y1 = event.getY();
initiateDrawParachuters();
return true;
}
public void initiateDrawParachuters()
{
drawParachuter1();
}
private void drawParachuter1() {
// TODO Auto-generated method stub
//Parachuter nr. 1
x = 68;
y = 40;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter2();
}
private void drawParachuter2() {
// TODO Auto-generated method stub
//Parachuter nr. 2
x = 100;
y = 80;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter3();
}
private void drawParachuter3() {
// TODO Auto-generated method stub
//Parachuter nr. 3
x = 150;
y = 120;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter4();
}
private void drawParachuter4() {
// TODO Auto-generated method stub
//Parachuter nr. 4
x = 170;
y = 150;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter5();
}
private void drawParachuter5() {
// TODO Auto-generated method stub
//Parachuter nr. 5
x = 180;
y = 170;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter6();
}
private void drawParachuter6() {
// TODO Auto-generated method stub
//Parachuter nr. 6
x = 200;
y = 180;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
}
public void drawParachuters()
{
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
}
public void setRunning(boolean bRun)
{
running = bRun;
}
public boolean getRunning()
{
return running;
}
}
/** Handle to the application context, used to e.g. fetch Drawables. */
private Context mContext;
/** Pointer to the text view to display "Paused.." etc. */
private TextView mStatusText;
/** The thread that actually draws the animation */
private ExampleThread eThread;
public ExampleView(Context context)
{
super(context);
// register our interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// create thread only; it's started in surfaceCreated()
eThread = new ExampleThread(holder, context, new Handler()
{
#Override
public void handleMessage(Message m)
{
// mStatusText.setVisibility(m.getData().getInt("viz"));
// mStatusText.setText(m.getData().getString("text"));
}
});
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
return eThread.onTouchEvent(event);
}
public ExampleThread getThread()
{
return eThread;
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder)
{
if (eThread.getState() == Thread.State.TERMINATED)
{
eThread = new ExampleThread(getHolder(), getContext(), getHandler());
eThread.start();
}
else
{
eThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
boolean retry = true;
eThread.setRunning(false);
while (retry)
{
try
{
eThread.join();
retry = false;
}
catch (InterruptedException e)
{
}
}
}
}
I agree with the others, check the value via Log messages, so you can see the actual values.
Also, check if it might go over 3. I dont know what kind of game you are making but for example, say that livesLeftValue=2 for now, but something happens, and it increases by 2, reaching 4, without ever having the value 3. Lets say it never gets decreased, so you will never ever hit the value 3, thus never invoking the game over thingie, and livesLeftValue will just increase to the infinity.
put some debug in there and see if you really get the right value in here.
private void checkLivesLeftValue() {
Log.d("checkLivesLeftValue", "lives = " + livesLeftValue);
if (livesLeftValue == 3) {
Log.d("checkLivesLeftValue", "calling onMethod now");
onMethod();
} else {
livesLeftValue = livesLeftValue + 1;
Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue);
}
}
public void onMethod() {
Log.d("onMethod", "in onMethod");
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("onMethod", "showing Toast now");
Toast.makeText(getContext(), "You lost!", 15).show();
}
});
}