I don't know why I confuse with simple if/ else condition? In my app, phone verification part, Bydefault I set sendVerification button disable, and when I enter text then it should enable. but it is not enabling? What is wrong with my condition? even if I try with else part, same problem!
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PhoneAuthActivity">
<include
android:id="#+id/PhoneToolbar"
layout="#layout/app_bar">
</include>
<LinearLayout
android:id="#+id/DialLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/PhoneToolbar"
android:orientation="horizontal"
android:weightSum="10">
<ImageView
android:id="#+id/dial"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="#drawable/dial"
android:layout_weight="1"/>
<EditText
android:id="#+id/PhoneNumber"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:layout_weight="8"
android:ems="10"
android:inputType="phone"/>
<ProgressBar
android:id="#+id/PhoneProgress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/LockLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/DialLayout"
android:orientation="horizontal"
android:weightSum="10">
<ImageView
android:id="#+id/lock"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="#drawable/lock"
android:layout_weight="1"/>
<EditText
android:id="#+id/code"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Verification Code"
android:layout_weight="8"/>
<ProgressBar
android:id="#+id/CodeProgress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<TextView
android:id="#+id/VerificationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="91dp"
android:text="A verification code will be sent to your phone number" />
<Button
android:id="#+id/sendVerification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:backgroundTint="#FF0000"
android:text="Send Verification" />
</RelativeLayout>
And this is Activity
package com.jimmytrivedi.lapitchat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneAuthActivity extends AppCompatActivity {
private LinearLayout DialLayout, LockLayout;
private EditText PhoneNumber, code;
private ProgressBar PhoneProgress, CodeProgress;
private Button sendVerification;
private Toolbar PhoneToolbar;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_auth);
DialLayout = findViewById(R.id.DialLayout);
LockLayout = findViewById(R.id.LockLayout);
PhoneNumber = findViewById(R.id.PhoneNumber);
code = findViewById(R.id.code);
PhoneProgress = findViewById(R.id.PhoneProgress);
CodeProgress = findViewById(R.id.CodeProgress);
sendVerification = findViewById(R.id.sendVerification);
PhoneToolbar = findViewById(R.id.PhoneToolbar);
PhoneProgress.setVisibility(View.INVISIBLE);
CodeProgress.setVisibility(View.INVISIBLE);
sendVerification.setEnabled(false);
setSupportActionBar(PhoneToolbar);
getSupportActionBar().setTitle("Welcome to Phone Verification");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
number = PhoneNumber.getText().toString();
if (!number.isEmpty()) {
sendVerification.setEnabled(true);
}
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PhoneNumber.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
};
}
}
number = PhoneNumber.getText().toString();
if (!number.isEmpty()) {
sendVerification.setEnabled(true);
}
This is all executed in onCreate before you get the chance to start typing. Once you start typing this code is not executed again. It is only executed once, when the activity is being created.
Solution: set up a TextWatcher on the phone number editText and enable/disable sendVerification in the TextWatcher#afterTextChanged method. See here for instructions on how to do it.
In your code
number = PhoneNumber.getText().toString();
if (!number.isEmpty()) {
sendVerification.setEnabled(true);
}
is executed only once at onCreate. You'll have to add a text change listener and enable/disable the button accordingly
like,
PhoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() > 0)
{
sendVerification.setEnabled(true);
}
}
});
You need a TextWatcher to do what you wish to do, so add a TextWatcher to your EditText/TextView like below:
PhoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length()>0) {
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
The reason your code wasn't working is because the onCreate() method does not get called after you start typing, meaning the condition for enabling your view is checked only once so any changes are not checked again.
Related
I have made three activities these are:
sendOTPone
verificationOTPtwo
dashboard
When I clicked on submit button from OTP verification screen then it will not let me go in dashboard screen my app closes automatically after this. Can anyone tell me where I did the mistake?
XML code for verificationOTPtwo
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never"
android:scrollbars="none"
tools:context=".verificationOTPtwo">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginTop="80dp"
android:contentDescription="#string/app_name"
android:src="#drawable/recieved" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="OTP Verififcation"
android:textColor="#color/colorTextFirst"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="50dp"
android:gravity="center"
android:text="Please enter the OTP sent to you"
android:textColor="#color/colorTextSecond"
android:textSize="14sp" />
<TextView
android:id="#+id/textmobileshownumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="50dp"
android:gravity="center"
android:textColor="#color/colorTextFirst"
android:textSize="14sp"
android:textStyle="bold" />
//###############################################
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:orientation="horizontal">
<EditText
android:id="#+id/inputotp1"
android:layout_width="40dp"
android:layout_height="46dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp2"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp3"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp4"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp5"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp6"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
</LinearLayout>
//################################################
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Not received OTP ?"
android:textColor="#color/colorTextSecond"
android:textSize="14sp" />
<TextView
android:id="#+id/textresendotp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="RESEND OTP AGAIN"
android:textColor="#color/colorTextFirst"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/buttonotpsubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="#drawable/backgroundbutton"
android:text="Submit"
android:textColor="#color/white"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressbar_verify_otp"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
</ScrollView>
Java code for verificationOTPtwo
package com.example.animatedsplashdemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class verificationOTPtwo extends AppCompatActivity {
EditText inputnumber1, inputnumber2, inputnumber3, inputnumber4, inputnumber5, inputnumber6;
String getotpbackend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_otptwo);
final Button verifyButtonClick = findViewById(R.id.buttonotpsubmit);
inputnumber1 = findViewById(R.id.inputotp1);
inputnumber2 = findViewById(R.id.inputotp2);
inputnumber3 = findViewById(R.id.inputotp3);
inputnumber4 = findViewById(R.id.inputotp4);
inputnumber5 = findViewById(R.id.inputotp5);
inputnumber6 = findViewById(R.id.inputotp6);
TextView textView = findViewById(R.id.textmobileshownumber);
textView.setText(String.format(
"+91-%s", getIntent().getStringExtra("mobile")
));
getotpbackend = getIntent().getStringExtra("backendotp");
final ProgressBar progressBarverifyotp = findViewById(R.id.progressbar_verify_otp);
verifyButtonClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!inputnumber1.getText().toString().trim().isEmpty() && !inputnumber2.getText().toString().trim().isEmpty() && !inputnumber3.getText().toString().trim().isEmpty() && !inputnumber4.getText().toString().trim().isEmpty() && !inputnumber5.getText().toString().trim().isEmpty() && !inputnumber6.getText().toString().trim().isEmpty()) {
String entercodeotp = inputnumber1.getText().toString() +
inputnumber2.getText().toString() +
inputnumber3.getText().toString() +
inputnumber4.getText().toString() +
inputnumber5.getText().toString() +
inputnumber6.getText().toString();
if (getotpbackend != null) {
progressBarverifyotp.setVisibility(View.VISIBLE);
verifyButtonClick.setVisibility(View.INVISIBLE);
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(
getotpbackend, entercodeotp
);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBarverifyotp.setVisibility(View.GONE);
verifyButtonClick.setVisibility(View.VISIBLE);
if (task.isSuccessful()) {
Intent intent = new Intent(getApplicationContext(), dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(verificationOTPtwo.this, "Enter the correct OTP", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(verificationOTPtwo.this, "Please check internet connection", Toast.LENGTH_SHORT).show();
}
// Toast.makeText(verificationOTPtwo.this, "OTP Verified", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(verificationOTPtwo.this, "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
});
numberotpmove();
TextView resendlabel = findViewById(R.id.textresendotp);
resendlabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+91" + getIntent().getStringExtra("mobile"),
60,
TimeUnit.SECONDS,
verificationOTPtwo.this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(verificationOTPtwo.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(#NonNull String newbackendotp, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
getotpbackend = newbackendotp;
Toast.makeText(verificationOTPtwo.this, "OTP sended successfully", Toast.LENGTH_SHORT).show();
}
}
);
}
});
}
private void numberotpmove() {
inputnumber1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber2.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber3.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber3.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber4.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber4.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber5.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber5.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber6.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
dashboard.java :
package com.example.animatedsplashdemo;
import android.os.Bundle;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
public class dashboard extends AppCompatActivity {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
drawerLayout = findViewById(R.id.drawerlayout);
navigationView = findViewById(R.id.navigationview);
toolbar = findViewById(R.id.toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_open, R.string.navigation_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
setSupportActionBar(toolbar);
}
}
Logcat:
2022-04-03 01:27:14.483 21162-21162/com.example.animatedsplashdemo
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.animatedsplashdemo, PID: 21162
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.animatedsplashdemo/com.example.animatedsplashdemo.dashboard}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1139)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:581)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:183)
at com.example.animatedsplashdemo.dashboard.onCreate(dashboard.java:32)
at android.app.Activity.performCreate(Activity.java:8198)
at android.app.Activity.performCreate(Activity.java:8182)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3765)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1139)
Set windowActionBar false in your AppTheme.
<item name="windowActionBar">false</item>
Hope this will help you.
In my chat app, I'm adding Phone verification from user. So I want that when user will enter the number, after that sendVerification button should be setEnabled(true) and I set setEnabled(false) as default, but when I run the app, it is still showing as enabled without entering the digits.
activity_phone_auth.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PhoneAuthActivity">
<include
android:id="#+id/PhoneToolbar"
layout="#layout/app_bar">
</include>
<LinearLayout
android:id="#+id/DialLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/PhoneToolbar"
android:orientation="horizontal"
android:weightSum="10">
<ImageView
android:id="#+id/dial"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="#drawable/dial"
android:layout_weight="1"/>
<EditText
android:id="#+id/PhoneNumber"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:layout_weight="8"
android:ems="10"
android:inputType="phone"/>
<ProgressBar
android:id="#+id/PhoneProgress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/LockLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/DialLayout"
android:orientation="horizontal"
android:weightSum="10">
<ImageView
android:id="#+id/lock"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="#drawable/lock"
android:layout_weight="1"/>
<EditText
android:id="#+id/code"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Verification Code"
android:layout_weight="8"/>
<ProgressBar
android:id="#+id/CodeProgress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<TextView
android:id="#+id/VerificationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="91dp"
android:text="A verification code will be sent to your phone number" />
<Button
android:id="#+id/sendVerification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:backgroundTint="#FF0000"
android:text="Send Verification" />
</RelativeLayout>
PhoneAuthActivity.java
package com.jimmytrivedi.lapitchat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneAuthActivity extends AppCompatActivity {
private LinearLayout DialLayout, LockLayout;
private EditText PhoneNumber, code;
private ProgressBar PhoneProgress, CodeProgress;
private Button sendVerification;
private Toolbar PhoneToolbar;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_auth);
DialLayout = findViewById(R.id.DialLayout);
LockLayout = findViewById(R.id.LockLayout);
PhoneNumber = findViewById(R.id.PhoneNumber);
code = findViewById(R.id.code);
PhoneProgress = findViewById(R.id.PhoneProgress);
CodeProgress = findViewById(R.id.CodeProgress);
sendVerification = findViewById(R.id.sendVerification);
PhoneToolbar = findViewById(R.id.PhoneToolbar);
PhoneProgress.setVisibility(View.INVISIBLE);
CodeProgress.setVisibility(View.INVISIBLE);
sendVerification.setEnabled(false);
setSupportActionBar(PhoneToolbar);
getSupportActionBar().setTitle("Welcome to Phone Verification");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
number = PhoneNumber.getText().toString();
if (number != null) {
sendVerification.setEnabled(true);
} else {
sendVerification.setEnabled(false);
}
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PhoneNumber.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
};
}
}
Use a TextWatcher() to know when the user enters the text in edit text. Do like this:-
Replace this:-
number = PhoneNumber.getText().toString();
if (number != null) {
sendVerification.setEnabled(true);
}
else {
sendVerification.setEnabled(false);
}
with this:-
PhoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String text = charSequence.toString();
if(!text.isEmpty()){
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!PhoneNumber.getText().toString().isEmpty()){
number = PhoneNumber.getText().toString();
PhoneNumber.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
else {
Toast.makeText(PhoneAuthActivity.this, "Empty Field", Toast.LENGTH_SHORT).show();
}
}
});
Replace
number = PhoneNumber.getText().toString();
if (number != null) {
sendVerification.setEnabled(true);
} else {
sendVerification.setEnabled(false);
}
with:
number = PhoneNumber.getText().toString();
if (number.isEmpty()) {
sendVerification.setEnabled(false);
} else {
sendVerification.setEnabled(true);
}
Set sendVerification.setEnabled(false) by default in onCreate(...) method and then apply TextChangedListener like this
PhoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equalsIgnoreCase("")) {
sendVerification.setEnabled(false);
} else {
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
It will automatically disable sendVerification Button whenever PhoneNumber is blank
I have a textview timer, i want it stops after 10 seconds of showing on display and after 10 seconds that my current activity jumps to an other activity
Runnable runnable = new Runnable()
{
#Override
public void run()
{
while(Running)
{
try{
Thread.sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
handler.post(new Runnable()
{
#Override
public void run()
{
number+=1;
tvTimer.setText(String.valueOf(number)); //With setting value of number on textfield ITS POSSIBLE TO SEE THE TIMER
if(number==10)
{
Running = false;
handler.removeCallbacks(this);//that does not works for me to stop
Intent i = new Intent(getApplicationContext(), SonucMenu.class);
startActivity(i); //Starting my second class
}
}
});
}
}
My Second activity starts but the layout from second activity comes more than one time, what i want is that it comes only one time, and i think this problem depends on that i cant stop runnable
Here My Complete original Code
MainActivity.class
package com.marburg.leftright;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import com.marburg.leftright.R;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
static Random rnd=new Random();
static int rndN = rnd.nextInt(2);
TextView inf,tvSc, tvTimer;
Button btnL, btnR;
int ScoreRhtg = 0;
int ScoreFls = 0;
String right = "RIGHT";
String left = "LEFT";
private int number;
private Handler handler;
private boolean Running = true;
MediaPlayer mySound;
public void sendData()
{
String rData = Integer.toString(ScoreRhtg); //Score Of Right Answer Data setting
String wData = Integer.toString(ScoreFls);
Intent i = new Intent(getApplicationContext(), SonucMenu.class);
i.putExtra("DATA", rData);
i.putExtra("DATA2", wData);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lr);
Intent intent = getIntent(); //Get Intent from SonucMenu.class to turn back MainActivity.java from New Button (This Class)
inf = (TextView)findViewById(R.id.tvInfo);
btnL = (Button)findViewById(R.id.btnL);
btnR = (Button)findViewById(R.id.btnR);
tvSc = (TextView)findViewById(R.id.tvScore);
//Set text left or right according new random number
if(rndN==1){
inf.setText(right);
}
else
{
inf.setText(left);
}
//Set 0 for Left
btnL.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{ //Set 0 for Left
if(rndN==0)
{
ScoreRhtg++;
tvSc.setText(ScoreRhtg+" Right");
rndN=rnd.nextInt(2); //Renew the random number
}
else
{
ScoreFls++;
tvSc.setText(ScoreFls+" False");
rndN=rnd.nextInt(2); //Renew the random number
}
//Set text left or right according new random number
if(rndN==1){
inf.setText(right);
}
else
{
inf.setText(left);
}
}
});
//Set 1 For Right
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(rndN==1)
{
ScoreRhtg++;
tvSc.setText(ScoreRhtg+" Right");
rndN=rnd.nextInt(2); //Renew the random number
}
else
{
ScoreFls++;
tvSc.setText(ScoreFls+" False");
rndN=rnd.nextInt(2); //Renew the random number
}
//Set text left or right according a new random number
if(rndN==1){
inf.setText(right);
}
else
{
inf.setText(left);
}
}
});
//FOR TIMER RESPONSIBLE PART OF CODE
tvTimer = (TextView)findViewById(R.id.tvTimer);
handler = new Handler();
Runnable runnable = new Runnable()
{
#Override
public void run()
{
while(Running)
{
try{
Thread.sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
handler.post(new Runnable()
{
#Override
public void run()
{
number+=1;
tvTimer.setText(String.valueOf(number)); //With setting value of number on textfield ITS POSSIBLE TO SEE THE TIMER
if(number==9)
{
mySound=MediaPlayer.create(MainActivity.this, R.raw.click);
mySound.start();
Running = false;
handler.removeCallbacks(this);//Doesnt works for me
sendData(); //sendData function startActivity(i) included
}
}
});
}
}
};
new Thread(runnable).start();
//END OF FOR TIMER RESPONSIBLE PART OF CODE
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my Second Class SonucMenu.java
package com.example.timerdeneme2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SonucMenu extends MainActivity {
public TextView tvCorr, tvWro;
public Button btnNew, btnCls;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sonuc_menu);
Intent i = getIntent();
Bundle dataBundle = i.getExtras();
String dataRString = dataBundle.getString("DATA");
String dataWString = dataBundle.getString("DATA2");
TextView tv = (TextView)findViewById(R.id.tvCorr);
TextView tvW = (TextView)findViewById(R.id.tvWro);
tv.setText(dataRString);
tvW.setText(dataWString);
btnNew = (Button)findViewById(R.id.btnNew);
btnNew.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(SonucMenu.this, MainActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
SonucMenu.this.startActivity(myIntent);
}
});
btnCls=(Button)findViewById(R.id.btnEx);
btnCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
}
}
And XML Layouts lr.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.marburg.leftright.MainActivity" >
<TextView
android:id="#+id/tvResCorr"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/tvResCorr"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/tvResCorr" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnL"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="L"
android:textSize="70dp" />
<Button
android:id="#+id/btnR"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="50dp"
android:text="R"
android:textSize="70dp" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
<TextView
android:id="#+id/tvInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableLayout1"
android:layout_alignRight="#+id/tableLayout1"
android:layout_below="#+id/tableLayout1"
android:layout_marginLeft="10dp"
android:layout_marginTop="200dp"
android:gravity="center"
android:text="Info"
android:textSize="24dp" />
<TextView
android:id="#+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableLayout1"
android:layout_alignRight="#+id/tableLayout1"
android:layout_below="#+id/tvInfo"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Score"
android:textSize="24dp" />
<TextView
android:id="#+id/tvTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:layout_centerHorizontal="true"
android:text="Time" />
</RelativeLayout>
And sonuc_menu.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.marburg.leftright.MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvResCorr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correctness:" />
<TextView
android:id="#+id/tvCorr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="X" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvResWro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wrongness" />
<TextView
android:id="#+id/tvWro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="X" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableLayout1"
android:layout_below="#+id/tableLayout1"
android:layout_marginTop="113dp" >
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnNew"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="NEW" />
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BEST SCORES" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<Button
android:id="#+id/btnEx"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="EXIT" />
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
</RelativeLayout>
I think for this you can use following code , It worked for me.
It will start your activity after 10 seconds.
new Handler().postDelay(new Runnable() {
#Override
public void run() {
Start Your activity here.
}
}, 10000);
but one of the best solution will be (I just found it from develoer site):
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
strat your activity here.
}
}.start();
Use View.post(Runnable) and View.postDelayed(Runnable, long), no need to create additional thread.
private TextView tvTimer;
private final Runnable mCountDownRunnable = new Runnable() {
private int mCount = 0;
#Override
public void run() {
mCount++;
if (mCount < 10) {
tvTimer.setText(Integer.toString(mCount));
tvTimer.postDelayed(this, 1000);
} else {
Intent i = new Intent(YourActivity.this, SonucMenu.class);
YourActivity.this.startActivity(i);
}
}
};
to start runnable, call tvTimer.post(mCountDownRunnable);
i read an example of how to show the progres of a seekbar to the edittext this is the web page:
Simple Seekbar In Android
now my problem is how to change the seekbar if i introduce a number inside the edittext box? thanks for any help
if you can acces the web page i will also post the code:
main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="94dp" >
<requestFocus />
</EditText>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="38dp" />
</RelativeLayout>
and the java code:
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class SeekbarActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SeekBar sb=(SeekBar) findViewById(R.id.seekBar1);
final EditText et=(EditText) findViewById(R.id.editText1);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser)
{
//---change the font size of the EditText---
et.setText(String.valueOf(progress));
}
});
}
}
Use addTextChangedListener
A quick example :
//et and sk are class variables
et=(EditText)findViewById(R.id.editText);
sk = (SeekBar)findViewById(R.id.seekBar);
et.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try{
//Update Seekbar value after entering a number
sk.setProgress(Integer.parseInt(s.toString()));
} catch(Exception ex) {}
}
});
Using my onEditTextchanger. It works fine when the user inputs 100000, in the EditText box it shows $100,000.00 as the user types. Which is correct.
The problem is however if I try to display a numeric keyboard rather than a Qwerty keyboard. By adding in the XML I add android: inputType=”numberDecimal” I lose the formatting of $ and the, and the EditText displays like 100000.00. I have noticed this happens if I change the InputType to Number or Decimal as well. I have attached the code.
Any ideas? Again Thanks in advance for your help.
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/txta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number2" />
<EditText
android:id="#+id/txtb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number3" />
<TextView
android:id="#+id/txtc"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Answer is"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtd"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
Java
public class CalcTestActivity extends Activity {
private EditText txta;
private EditText txtb;
private TextView txtc;
private TextView txtd;
private double a = 0;
private double b = 0;
private double c = 0;
private double d = 0;
private Button buttonCalc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
txta.addTextChangedListener(new CurrencyTextWatcher());
txtb.addTextChangedListener(new CurrencyTextWatcher());
}
private void initControls() {
txta = (EditText)findViewById(R.id.txta);
txtb = (EditText)findViewById(R.id.txtb);
txtc = (TextView)findViewById(R.id.txtc);
txtd = (TextView)findViewById(R.id.txtd);
buttonCalc = (Button)findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {calculate(); }});}
private void calculate() {
a=Double.parseDouble(txta.getText().toString().replace("$", "").replace(",", ""));
b=Double.parseDouble(txtb.getText().toString().replace("$", "").replace(",", ""));
c=Math.round(a*.88);
txtc.setText(GlobalMoney.FormatValue(c));
d=Math.round((a*.87)+(b*.61)*(c*.25));
txtd.setText(GlobalMoney.FormatValue(d));
}
}
TextWatcher
import java.text.NumberFormat;
import android.text.Editable;
import android.text.TextWatcher;
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
public CurrencyTextWatcher() {
mEditing = false;
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
By default, inputType=”numberDecimal” doesn't accept any special characters except .(dot). May be you need to do some hack to make this work. There is an interesting SO discussion to hack in special character ','. You may try that to have $ symbol. Here is link.