TextEdit validation overlays show password icon - android

I have a password TextEdit field that im currently doing validation on and it displays an icon at the end of the TextEdit field to toggle the actual text. When someone enterted in a incorrect password or the passwords dont match it displays an error icon indicating that there was an error with the text entered and this error icon goes right underneath the "show text" icon for the TextEdit field. How do I move either the error icon from validation, or how do I move the "show text" icon?
app displaying both error icon and show text icon
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
#InjectView(R.id.input_name) EditText _nameText;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.input_confirmPassword) EditText _confirmPasswordText;
#InjectView(R.id.btn_signup) Button _signupButton;
#InjectView(R.id.link_login) TextView _loginLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.inject(this);
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
finish();
}
});
}
public void signup() {
Log.d(TAG, "Begin Signup process...");
if (!validate()) {
onSignupFailed();
return;
}
_signupButton.setEnabled(false);
final ProgressDialog signupProgressDialog = new ProgressDialog(RegisterActivity.this,
R.style.Theme_IAPTheme);
signupProgressDialog.setIndeterminate(true);
signupProgressDialog.setMessage("Creating Account...");
signupProgressDialog.show();
String name = _nameText.getText().toString();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
String confirmPassword = _confirmPasswordText.getText().toString();
// TODO: Implement your own signup logic here.
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.i("tagconvertstr", "["+response+"]");
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
onSignupSuccess();
} else {
onSignupFailed();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
/*new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onSignupSuccess or onSignupFailed
// depending on success
onSignupSuccess();
// onSignupFailed();
progressDialog.dismiss();
}
}, 3000);*/
}
public void onSignupSuccess() {
Toast.makeText(getBaseContext(), "Signup Successful", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Signup Failed", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
boolean psisequal;
String name = _nameText.getText().toString();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
String confirmPassword = _confirmPasswordText.getText().toString();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
}else {
_passwordText.setError(null);
}
if (password.equals(confirmPassword)){
_confirmPasswordText.setError(null);
psisequal = true;
}else {
_confirmPasswordText.setError("passwords do not match");
valid = false;
psisequal = false;
}
return valid;
}
}
activity_register
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true"
android:background="#color/black">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" />
<!-- Name Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff">
<EditText android:id="#+id/input_name"
android:theme="#style/MyEditTextTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
android:hint="Trainer Name (Gamer Tag)" />
</android.support.design.widget.TextInputLayout>
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff">
<EditText android:id="#+id/input_email"
android:theme="#style/MyEditTextTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="E-Mail Address" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff">
<EditText android:id="#+id/input_password"
android:theme="#style/MyEditTextTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Confirm Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff">
<EditText android:id="#+id/input_confirmPassword"
android:theme="#style/MyEditTextTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Confirm Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Create Account"/>
<TextView android:id="#+id/link_login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Already a member? Login"
android:textColor="#ffffff"
android:gravity="center"
android:textSize="16dip"/>
</LinearLayout>
</ScrollView>
Strings
<resources xmlns:android="http://schemas.android.com/tools">
<string name="app_name">The World of Go</string>
<string name="title_activity_maps">Map</string>
<!--CODE FOR BUTTON OVERLAY-->
<string name="Popular"></string>
<string name="AZ"></string>
<string name="Category"></string>
<string name="NearBy"></string>
<color name="bg_color">#ffffff</color>
<color name="black">#222222</color>
<color name="white">#ffffff</color>
<style name="MyEditTextTheme">
<item name="colorControlNormal">#ffffff</item>
<item name="colorControlActivated">#ffffff</item>
<item name="colorControlHighlight">#ffffff</item>
<item name="colorAccent">#android:color/white</item>
<item name="android:textColor">#ffffff</item>
<item name="android:textColorHint">#ffffff</item> />
</style>
<string name="type_prompt">Choose a Type</string>
<string-array name="type_arrays">
<item>Pokestop</item>
<item>Gym</item>
</string-array>
</resources>

Try these methods to apply validation check:
private TextInputLayout text_email,text_pass, text_confirm_pass;
private EditText email,pass,confirm_pass;
text_pass = (TextInputLayout) findViewById(R.id.input_layout_password);
email = (EditText) findViewById(R.id.email);
private boolean validatePassword() {
if (pass.getText().toString().trim().isEmpty()) {
pass.setError(getString(R.string.err_msg_pass));
requestFocus(text_pass);
return false;
}else if(pass.getText().toString().length()<8) {
pass.setError(getString(R.string.err_msg_pass_length));
requestFocus(text_pass);
return false;
}else {
text_pass.setErrorEnabled(false);
}
return true;
}
To get focus :
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}

Here is my solution
login xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey"
android:fillViewport="true">
<LinearLayout
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:text="LOGIN"
android:textSize="25sp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff">
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Trainer Name (Gamer Tag)"
android:inputType="textCapWords"
android:padding="10dp"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:textColor="#ffffff"
android:textColorHint="#ffffff">
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="#drawable/ic_visibility_off_white_24dp"
android:hint="Password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/btnSignIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="Sign In"
android:textColor="#android:color/white" />
</LinearLayout>
</RelativeLayout>
Login class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnLogin;
private EditText etUserName, etPassword;
private String userName, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initValues();
}
private void initValues() {
try {
btnLogin = (Button) findViewById(R.id.btnSignIn);
btnLogin.setOnClickListener(this);
etUserName = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
etPassword.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (event.getRawX() >= (etPassword.getRight() - etPassword.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
if (etPassword.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
etPassword.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
etPassword.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_visibility_off_white_24dp, 0);
etPassword.setSelection(etPassword.getText().length());
} else {
etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
etPassword.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_visibility_white_24dp, 0);
}
return true;
}
}
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.btnSignIn:
validateCredentials();
onLogin();
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void validateCredentials() {
try {
userName = etUserName.getText().toString();
password = etPassword.getText().toString();
if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
etUserName.setError("enter a valid username");
etPassword.setError("enter a correct password");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onLogin() {
//your login implementation
}
}
Screenshots

So here is what I had to do to fix this. I disabled the standard text view of the textEdit by doing the following:
app:passwordToggleEnabled="false"
This will disable the view of the icon to toggle the password visibility. Then What I did was to add an imageView and added my own eye icon to the app:
<ImageView
android:id="#+id/imageView_registerPasswordVisibility"
android:layout_width="24dp"
android:layout_height="24dp"
android:clickable="true"
android:src="#drawable/eye"
android:layout_row="4"
android:layout_column="1"
android:foregroundGravity="center_vertical"
android:layout_gravity="center_vertical" />
I converted my layout to a grid layout and put this image view in the next column to align it to the end of the textEdit, the reason behind this is cause we now show the icon AFTER the textEdit instead of inside the textEdit which where the error validation icon will appear. Doing this will fix the conflict, I handled the imageView to do the same thing as passwordToggle. So here is the entire code for all of that which will also show how to set errors properly on the TextInputLayout if that is what you are using. If not then set errors as you would normally (can be found in standard android documentation):
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
//Setup global variables for all of the user interface items.
#InjectView(R.id.wrapper_registerPassword)
TextInputLayout _registerPasswordWrapper; /*this is only needed for when you use TextInputLayout that gives us the ability to have animated hints by default. If you are ONLY using editText then you will not need the code for this wrapper.*/
#InjectView(R.id.editText_registerPasswordInput)
EditText _registerPasswordInput; /*This is to access text that was typed in the editText*/
#InjectView(R.id.imageView_registerPasswordVisibility)
ImageView _registerPasswordVisibility; /*This is used for our image that we will be adding listeners for to do speacial features when the image is pressed. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.inject(this);
/*Set a listener for the password view image to display the text inside the password text
field for when the image is pressed.*/
_registerPasswordVisibility.setOnTouchListener(mPasswordVisibleTouchListener);
}
/*Listener for the toggle password icon.*/
private View.OnTouchListener mPasswordVisibleTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final boolean isOutsideView = event.getX() < 0 ||
event.getX() > v.getWidth() ||
event.getY() < 0 ||
event.getY() > v.getHeight();
// change input type will reset cursor position, so we want to save it
final int cursor = _registerPasswordInput.getSelectionStart();
if (isOutsideView || MotionEvent.ACTION_UP == event.getAction())
/*This will make the field display dots as a password text field should look like.*/
_registerPasswordInput.setInputType( InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
else
/*This will make the text in the password text field visibile while we are pressing down on our image.*/
_registerPasswordInput.setInputType( InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
_registerPasswordInput.setSelection(cursor);
return true;
}
};
public boolean validate() {
boolean valid = true;
//Obtain user's entered in credentials to validate them.
String password = _registerPasswordInput.getText().toString();
//Password validation.
if (password.isEmpty() || password.length() < 8 || password.length() > 30) {
_registerPasswordWrapper.setError("Please provide a stronger password.\n" +
"•Password must be the following:\n" +
"•At least 8 characters");
_registerPasswordWrapper.setErrorEnabled(true);
valid = false;
}else {
_registerPasswordWrapper.setError(null);
}
return valid;
}
}
activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android.support.design="http://schemas.android.com/tools"
android:fitsSystemWindows="true"
android:background="#color/black">
<!-- Start of Grid Layout -->
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:orientation="vertical">
<!-- Password Text Field -->
<android.support.design.widget.TextInputLayout
android:id="#+id/wrapper_registerPassword"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:textColor="#ffffff"
app:passwordToggleEnabled="false"
android:textColorHint="#ffffff"
android:layout_column="0"
android:layout_row="4"
android:layout_gravity="fill_horizontal">
<android.support.design.widget.TextInputEditText
android:id="#+id/editText_registerPasswordInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="30"
android:inputType="textPassword"
android:hint="Password" />
</android.support.design.widget.TextInputLayout>
<!-- Password Toggle Icon for Password field -->
<ImageView
android:id="#+id/imageView_registerPasswordVisibility"
android:layout_width="24dp"
android:layout_height="24dp"
android:clickable="true"
android:src="#drawable/eye"
android:layout_row="4"
android:layout_column="1"
android:foregroundGravity="center_vertical"
android:layout_gravity="center_vertical" />
</GridLayout>
</ScrollView>
I hope this helps out some people, if anyone has anymore questions please let me know and ill help out to the best of my abilities!

If you're looking to only have one icon displayed this could do the trick.
Change the PasswordVisibilityToggleTintMode property.
You can hide the password toggle icon via:
setPasswordVisibilityToggleTintMode(PorterDuff.Mode.CLEAR)
Make it visible again via:
setPasswordVisibilityToggleTintMode(PorterDuff.Mode.MULTIPLY)

Please use app:endIconDrawable="#null" for TextInputLayout in your xml.

First, you need to wrap your edit text in an TextInputLayout.
Then, you should set the errorIconDrawable to null when you set the text error to something, so it won't override the toggle password icon.
Like this:
if (hasError) {
textInputLayout.error = "Error text"
textInputLayout.errorIconDrawable = null
}

It is easier to use:
TextInputLayout.isEndIconVisible
you can show or hide the Eye icon by setting it true or false.
for example when there is an error do this to hide the eye icon so the error icon is visible:
passwordTextInputLayout.isEndIconVisible = false
and then when the user starts typing again show it like this:
passTextView.afterTextChanged {
passwordTextInputLayout.isEndIconVisible = true
}

Related

Save and list contents in android

So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:onClick="save"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:onClick="list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
This is the XML for the second Activity which will be opened when the list button is clicked:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show"
android:scrollbars="horizontal|vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="63dp" />
<TextView
android:text="#string/list_of_saved_url_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:id="#+id/textView"
android:textColor="#color/colorAccent"
android:textSize="24sp" />
</RelativeLayout>
This is my main class:
public class MainActivity extends AppCompatActivity {
private EditText url;
private Button save;
ArrayList<String> addArray = new ArrayList<String>();
private Button list;
private ListView show1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
list = (Button)findViewById(R.id.btn_list);
show1 = (ListView)findViewById(R.id.show);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = url.getText().toString();
if(addArray.contains(getInput))
{
Toast.makeText(getBaseContext(), "URL already added to the list!", Toast.LENGTH_LONG).show();
}
else if(getInput == null || getInput.trim().equals(""))
{
Toast.makeText(getBaseContext(), "Input field is empty!", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
((EditText)findViewById(R.id.txtbox_website)).setText("");
}
}
});
}
public void list(View view) {
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent screen = new Intent(MainActivity.this, Activity2.class);
startActivity(screen);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}http://www.stackoverflow.com
return super.onOptionsItemSelected(item);
}
}
My save button and list button is not able to save and list the URLs entered by the user.
What should I add?
Thanks
1) Not Saving:
Currently you are storing data statically inside your addArray object. Which gets cleared when you close app.
I think better to use persist data storage. So you can retrieve already stored websites when app re-launched. (Like browser manages history). Available storage options
2) Not showing list:
You need to pass your current list of urls (i.e. addArray variable) in bundle when starting Activity2 And read that list inside Activity2 onCreate. Find here.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
You don't need this list adapter inside your main activity, You need to create it inside Activity2 and set this adapter in your listview.
I hope it will help you fix your issues.

Edit text Password Toggle Android

I am trying to show user the typed password in edit text whose input type is text Password.
I implemented gesturelistener over the toggle icon like this-
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (view.getId())
{
case R.id.ivPasswordToggle:
switch ( motionEvent.getAction() ) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(getContext(),"show",Toast.LENGTH_SHORT).show();
etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
break;
case MotionEvent.ACTION_UP:
etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
Toast.makeText(getContext(),"hide",Toast.LENGTH_SHORT).show();
break;
}
break;
}
return true;
}
i dont know what is wrong, any help will be appreciated.
(updated for AndroidX)
Since the Support Library v24.2.0. you can achivie this very easy
What you need to do is just:
Add the design library to your dependecies
dependencies {
implementation "com.google.android.material:material:1.2.1"
}
Use TextInputEditText in conjunction with TextInputLayout
<com.google.android.material.textfield.TextInputLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/etPasswordLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true">
<android.support.design.widget.TextInputEditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password_hint"
android:inputType="textPassword"/>
</com.google.android.material.textfield.TextInputLayout>
passwordToggleEnabled attribute will make the password toggle appear
In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"
You can customize your password toggle by using:
app:passwordToggleDrawable - Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint - Icon to use for the password input visibility toggle.
app:passwordToggleTintMode - Blending mode used to apply the background tint.
More details in TextInputLayout documentation.
Please try this code.
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (view.getId())
{
case R.id.ivPasswordToggle:
switch ( motionEvent.getAction() ) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(getContext(),"show",Toast.LENGTH_SHORT).show();
etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
break;
case MotionEvent.ACTION_UP:
etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
Toast.makeText(getContext(),"hide",Toast.LENGTH_SHORT).show();
break;
}
break;
}
return true;
}
I hope it will work, thanks.
If you don't want any extra bool or dependencies, then
<EditText
android:id="#+id/et_input_pass"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginTop="3dp"
android:layout_marginStart="56dp"
android:layout_marginEnd="56dp"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true"
android:textSize="13sp"
android:background="#color/transparent"
android:theme="#style/MyEditText" />
and
password_toggle_imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (et_input_pass.getTransformationMethod().getClass().getSimpleName() .equals("PasswordTransformationMethod")) {
et_input_pass.setTransformationMethod(new SingleLineTransformationMethod());
}
else {
et_input_pass.setTransformationMethod(new PasswordTransformationMethod());
}
et_input_pass.setSelection(et_input_pass.getText().length());
}
});
that's it!
Try the following method. Here, we are setting a compound drawable which when clicked will show or hide the password:
private boolean passwordShown = false;
private void addPasswordViewToggle() {
getPasswordEditText().setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2; //index
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (getPasswordEditText().getRight() - getPasswordEditText().getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
if (passwordShown) {
passwordShown = false;
// 129 is obtained by bitwise ORing InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
getPasswordEditText().setInputType(129);
// Need to call following as the font is changed to mono-space by default for password fields
getPasswordEditText().setTypeface(Typeface.SANS_SERIF);
getPasswordEditText().setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.locked_icon, 0); // This is lock icon
} else {
passwordShown = true;
getPasswordEditText().setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
getPasswordEditText().setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.unlocked_icon, 0); // Unlock icon
}
return true;
}
}
return false;
}
});
}
fragmentLoginBinding.imageViewEye.setOnClickListener(v -> {
if (!isPasswordVisible) {
fragmentLoginBinding.editTextPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
fragmentLoginBinding.imageViewEye.setImageDrawable(getResources().getDrawable(R.mipmap.feather_eye_crossed));
isPasswordVisible = true;
} else {
fragmentLoginBinding.editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
fragmentLoginBinding.imageViewEye.setImageDrawable(getResources().getDrawable(R.mipmap.feather_eye));
isPasswordVisible = false;
}
});
app:passwordToggleEnabled="true"
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true">
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
If you want to use an EditText or AppCompatEditText you can implement that desired output by;
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/spinner_role"
>
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/edit_text_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:autofillHints="#string/password"
android:hint="#string/password"
android:inputType="textPassword"
android:textSize="16sp"
app:backgroundTint="#59A6B6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/button_password_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:src="#drawable/ic_visibility_off"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/register_user_password_et" />
</androidx.constraintlayout.widget.ConstraintLayout>
In your .kt file;
if (registerUserBinding.editTextPassword.transformationMethod.equals(
PasswordTransformationMethod.getInstance()
)
) {
registerUserBinding.registerUserPasswordEt.transformationMethod =
HideReturnsTransformationMethod.getInstance()
registerUserBinding.buttonPasswordToggle.setImageDrawable(
ContextCompat.getDrawable(
registerUserBinding.registerUserPasswordEt.context,
R.drawable.ic_visibility
)
)
} else {
registerUserBinding.editTextPassword.transformationMethod =
PasswordTransformationMethod.getInstance()
registerUserBinding.buttonPasswordToggle.setImageDrawable(
ContextCompat.getDrawable(
registerUserBinding.registerUserPasswordEt.context,
R.drawable.ic_visibility_off
)
)
}
Implement the TextInput like below. The main attribute that gives that feature is app:passwordToggleEnabled="true"
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/resetpasswordactivity_textinputlayout_newpassword"
android:layout_width="0dp"
android:layout_height="60dp"
app:passwordToggleEnabled="true"
android:theme="#style/loginActivityHintStyle"
app:layout_constraintBottom_toTopOf="#+id/resetpasswordactivity_textinputlayout_newconfirmpassword"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/resetpasswordactivity_textinputlayout_resetcode"
app:layout_constraintVertical_bias="0.15">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/resetpasswordactivity_textinputedittext_newpassword"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Password"
android:inputType="textPassword"
android:labelFor="#id/resetpasswordactivity_textinputedittext_newpassword"
android:maxLength="100"
android:textColor="#drawable/black_inputtext_color"
/>
</com.google.android.material.textfield.TextInputLayout>
This is a little addition to the accepted answer for those, who wondering who to implement custom drawable for toggle
In your resources:
drawable/password_toggle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:state_checked="true"
android:drawable="#drawable/eye"
app:tint="#color/black_600_8a"/>
<item
android:drawable="#drawable/eye_closed"
app:tint="#color/black_600_8a" />
</selector>
state_checked is the state when password is visible
Note: use app:tint in the drawable and not android:endIconTint in the layout to change the colour of your toggle, as the latter won't work properly with selector
In your layout xml
<com.google.android.material.textfield.TextInputLayout
...
app:endIconMode="password_toggle"
app:endIconDrawable="#drawable/password_toggle">
<com.google.android.material.textfield.TextInputEditText
...
android:inputType="textPassword"/>
</com.google.android.material.textfield.TextInputLayout>
Hope this will help someone as much as it helped me!

Creating a new user in database

I am having an issue creating a new user with parse.com.. My code seems correct but for some reason whenever i enter a new user, it does not register.. Can someone help me with this issue?
final EditText newuser = (EditText) this.findViewById(R.id.newuser);
final EditText newuserpassword = (EditText) this.findViewById(R.id.newuserpassword);
final EditText EmailAddress = (EditText) this.findViewById(R.id.user_email);
TextView neighbourView = new TextView(this);
Button button_test2;
button_test2 = (Button) this.findViewById(R.id.button);
button_test2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View s) {
final String newusersname = newuser.getText().toString();
final String newpasswoord = newuserpassword.getText().toString();
final String newusermail = EmailAddress.getText().toString();
ParseUser user = new ParseUser();
user.setUsername(String.valueOf(newusersname));
user.setPassword(String.valueOf(newpasswoord));
user.setPassword(String.valueOf(newusermail));
user.signUpInBackground(new SignUpCallback() {
#Override
public void done( com.parse.ParseException e) {
if (e == null) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
Toast.makeText(getApplicationContext(), "choose a differnt username or password", Toast.LENGTH_LONG).show();
}
//if e != null, something went wrong
}
});
}
});
My XML is
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="New User Name"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:inputType="textPersonName"
android:id="#+id/newuser" />
<!-- Password Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="#string/password"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:password="true"
android:inputType="textPassword"
android:id="#+id/newuserpassword"
android:layout_gravity="center_horizontal" />
<!-- Email Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="E-Mail"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:inputType="textEmailAddress"
android:id="#+id/user_email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
And here is my ParseApplication method
public class ParseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
Parse.initialize(this, "xxxxxx ", "xxxx");
//...Rest of the Parse initializations.
}
Any assistance would be greatly appreciated.
You might not have logged out from your previous session. Add a log out logic and check.
Replace this
final String newusersname = newuser.getText().toString();
final String newpasswoord = newuserpassword.getText().toString();
final String newusermail = EmailAddress.getText().toString();
ParseUser user = new ParseUser();
user.setUsername(String.valueOf(newusersname));
user.setPassword(String.valueOf(newpasswoord));
user.setPassword(String.valueOf(newusermail));
with this
final String newusersname = newuser.getText().toString();
final String newpasswoord = newuserpassword.getText().toString();
final String newusermail = EmailAddress.getText().toString();
if(ParseUser.getCurrentUser()!=null)
{
ParseUser.getCurrentUser().logOut();
}
ParseUser user = new ParseUser();
user.setUsername(String.valueOf(newusersname));
user.setPassword(String.valueOf(newpasswoord));
user.setPassword(String.valueOf(newusermail));
try this saveInBackground() method that save the user.
ParseUser user = new ParseUser();
user.setUsername(String.valueOf(newusersname));
user.setPassword(String.valueOf(newpasswoord));
user.setPassword(String.valueOf(newusermail));
user.saveInBackground();
I'm New to this but I think the issue maybe that you trying to assign 2 passwords,
for my understanding its a field you cant duplicate and granted email has a separate field already built inside the user object
user.setUsername(String.valueOf(newusersname));
user.setPassword(String.valueOf(newpasswoord));
user.setEmail(String.valueOf(newusermail));

How to prevent to close dialog when a user input error information and click "Save" button in Android

I have setup a custom Preference that must launch a dialog with 3 TextViews to confirm and change a password.
I hope that the dialog will not be closed and display a prompt information if a user input error information and click "Save" button, how can I do? Thanks!
BTW, is it suitable to use DialogPreference control to deal with the business logic in PreferenceScreen ?
public class DialogChangePassword extends DialogPreference {
private String strPass1;
private String strPass2;
public DialogChangePassword(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.unlock_custom_dialog);
}
private View view;
#Override
protected View onCreateDialogView() {
// TODO Auto-generated method stub
view=super.onCreateDialogView();
return view;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
final EditText password1 = (EditText) view.findViewById(R.id.EditText_Pwd1);
final EditText password2 = (EditText)view.findViewById(R.id.EditText_Pwd2);
strPass1 = password1.getText().toString();
strPass2 = password2.getText().toString();
if (strPass1.equals(strPass2)) {
SavePassword();
super.onDialogClosed(positiveResult);
} else {
Toast.makeText(view.getContext(),"Input Error",Toast.LENGTH_LONG).show();
//Prevent to close the dialog! How to do?
}
}
}
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="AppPreference"
android:summary="#string/PreferenceSummary"
android:title="#string/Preference" >
<ui.custom.DialogChangePassword
android:key="prefKeyResetQuests"
android:dialogIcon="#android:drawable/ic_dialog_alert"
android:title="Reset Password"
android:summary="Reset Password"
android:dialogMessage="Reset Password"
android:positiveButtonText="Save"
android:negativeButtonText="Cancel"/>
/>
</PreferenceScreen>
unlock_custom_dialog.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/root"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/TextView_Pwd1"
android:text="string/settings_oldpassword"
android:textStyle="bold" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/EditText_OldPwd" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/TextView_Pwd11"
android:text="string/settings_password"
android:textStyle="bold" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/EditText_Pwd1"
android:inputType="textPassword" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/TextView_Pwd2"
android:text="string/settings_password2"
android:textStyle="bold" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/EditText_Pwd2"
android:inputType="textPassword" />
</LinearLayout>
Use this inside your DialogPreference :
#Override
public void onClick(DialogInterface dialog, int which)
{
// If the user clicked "Ok" but the "savePassword" function returns false (mainly because the checks weren't good), we block the closing of the Dialog
if (which == DialogInterface.BUTTON_POSITIVE && !savePassword())
{
try
{
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, false);
}
catch (NoSuchFieldException | IllegalAccessException e)
{
e.printStackTrace();
}
}
// else, we remove the block if it was put before
else
{
try
{
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, true);
}
catch (NoSuchFieldException | IllegalAccessException e)
{
e.printStackTrace();
}
}
}
This way, if the user want to leave the dialog before or after a failed validation, he still can. But the window won't close if the input is wrong and the user clicked "Ok".
PS : If you want to extendDialogPreference, you'll need this :
#Override
protected void onDialogClosed(boolean exitedViaOk)
{
super.onDialogClosed(exitedViaOk);
// Save only if the user clicked the "Ok" button
if (exitedViaOk)
{
savePassword();
}
}

myEditText.setText not refreshing on page

I have a simple activity which needs to accept a 4-digit PIN number using a custom pin-pad (buttons on the screen). The digits are stored in four EditTexts.
When I click a button, the text in the button is stored in a char[] (myEditText.getText() shows that this is happening), the focus is moved to the next EditText through an onFocusListener() and the Log output shows that this is all happening correctly.
11-20 10:19:56.969: I/DebugA(17742): Pin1 updated to: 1 // Pin1 is the ID
11-20 10:19:58.289: I/DebugA(17742): Pin2 updated to: 2 // '2' is Pin2.getText()
11-20 10:19:58.849: I/DebugA(17742): Pin3 updated to: 3
11-20 10:19:59.659: I/DebugA(17742): Pin4 updated to: 4
The screen itself is simply not being updated. The EditTexts all appear empty, even though the code executes perfectly.
I have looked through a whole heap of answers on SO and tried many of the suggestions with absolutely no luck, so I am posting this question which I hope someone can shed some light on! Has anyone else had this happen?
Here's some of the layout file:
<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" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" >
<EditText
android:id="#+id/Pin1"
android:tag="Pin1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="2"
android:gravity="center_vertical|center_horizontal"
android:nextFocusDown="#+id/Pin2"
android:maxLength="1"
android:inputType="textPassword" />
...
...
...
</RelativeLayout>
...and the buttons are:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:layout_below="#+id/layout1" >
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btnPinClick"
android:text="1" />
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btnPinClick"
android:layout_marginLeft="21dp"
android:text="2" />
<Button
android:id="#+id/Button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btnPinClick"
android:layout_marginLeft="21dp"
android:text="3" />
</LinearLayout>
The activity is a standard activity (MyActivity extends Activity).
Any thoughts?
UPDATE
Here's some of the java as requested:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout)inflater.inflate(R.layout.activity_login, null);
EditText Pin1 = (EditText) layout.findViewById(R.id.Pin1);
Pin1.setOnFocusChangeListener(focusListener);
Pin1.setText("1"); // <--THIS HAS NO EFFECT
EditText Pin2 = (EditText) layout.findViewById(R.id.Pin2);
Pin2.setOnFocusChangeListener(focusListener);
EditText Pin3 = (EditText) layout.findViewById(R.id.Pin3);
Pin3.setOnFocusChangeListener(focusListener);
EditText Pin4 = (EditText) layout.findViewById(R.id.Pin4);
Pin4.setOnFocusChangeListener(focusListener);
...
...
...
}
The Onclick method is:
public void btnPinClick(View btnPin) {
String PinNumber = ((Button)btnPin).getText().toString();
RelativeLayout layout = (RelativeLayout)getLayoutInflater().inflate(R.layout.activity_login, null);
ArrayList<View> views = (ArrayList<View>) layout.getFocusables(View.FOCUS_DOWN);
EditText nextItem = null;
for (int i = 0; i < views.size(); i++) {
// THIS IS THE CORRECT EditText FOR EACH OF THESE
EditText textBox = (EditText) views.get(i);
if (textBox.getTag().toString().equals(currentText)) {
textBox.setText(PinNumber);
pin[i] = PinNumber.toCharArray()[0];
Log.i("DebugA", textBox.getTag().toString() + " updated to: " + textBox.getText().toString());
textBox.invalidate();
textBox.refreshDrawableState();
if(i+1 < views.size()) {
nextItem = (EditText) views.get(i+1);
}
else {
doCheckPin();
}
break;
}
}
if(nextItem != null){
nextItem.requestFocus();
currentText = nextItem.getTag().toString();
}
}
UPDATE 2
Here is the code for the OnFocusChangeListener as requested:
protected OnFocusChangeListener focusListener = new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
//THIS SIMPLY SETS A VARIABLE STRING TO SAY WHICH
//EditText HAS FOCUS.
currentText = v.getTag().toString();
}
}
};
It looks like you're using a layout inflater in addition to setContentView in your activity. And affecting the edittexts referenced by the inflater. Try removing use of the inflater and rely solely on setContentView for this part of the activity. You might be performing in an incorrect view hierarchy.

Categories

Resources