Keyboard bugs after first letter in EditText - android

In my first activity when i select the text edit the keyboards appears.
When i write one letter the page scrolls as if the edit text had lost focus (but it didn't) and keyboard stay displayed even if it is not there (if i click approximately on the edit text under the displayed keyboard the keyboard entrance animation start again and everything works). I don't know what to do, look's really like a bug to me. Oh and, the bug only appears on this activity (the first activity to start), Android 8.1 Code and screens :
Edit text before bug
Ghost keyboard (you see it but it is not there, if i click the home button then come back, the keyboard disapeared and i can interract with the button and edit text under)LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private EditText e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final Button b = findViewById(R.id.startButton);
e = findViewById(R.id.name_input);
//if i click button or enter get to nex activity
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate();
}
});
e.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
validate();
return true;
}
return false; // i don't know android that much, but i don't think there is a problem here
}
});
//testing purpose
e.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Log.e("ERROR", "LOST FOCUS"); //Never called
} else {
Log.e("ERROR", "GOT FOCUS");
}
}
});
//For the ui style, commenting it changes nothing
final View decorView = getWindow().getDecorView();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
decorView.setSystemUiVisibility(uiOptions);
decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int visibility) {
if((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(uiOptions);
}
}
});
}
#Override protected void onPause() {
super.onPause();
}
#Override protected void onResume() {
super.onResume();
}
private void validate() {
if (!e.getText().toString().isEmpty() && e.getText().toString().length() < 16) {
SharedInfos.setName(e.getText().toString());
Log.e("Name : ", e.getText().toString());
Intent activityLaunch = new Intent(this, PresentationActivity.class);
this.startActivity(activityLaunch);
} else {
Toast.makeText(LoginActivity.this, "Name must be not empty and less than 16 char long !", Toast.LENGTH_LONG).show();
}
}
}
activity_main.xml (layout)
<android.support.constraint.ConstraintLayout 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"
tools:context=".LoginActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="343dp"
android:layout_height="336dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:contentDescription="Cat"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_foreground" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/carter_one"
android:text="#string/app_name"
android:textColor="#color/accent_material_dark_1"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="#+id/imageView"
app:layout_constraintStart_toStartOf="#+id/imageView"
app:layout_constraintTop_toTopOf="#+id/imageView"
app:layout_constraintVertical_bias="0.9" />
<Button
android:id="#+id/startButton"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:fontFamily="#font/carter_one"
android:text="#string/app_then"
android:textColor="#color/accent_material_dark_1"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/name_input"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/name_input" />
<EditText
android:id="#+id/name_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:ems="10"
android:fontFamily="#font/carter_one"
android:hint="#string/field_name"
android:inputType="text|textNoSuggestions|textVisiblePassword"
android:textColor="#color/accent_material_dark_1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/startButton"
app:layout_constraintHorizontal_bias="0.51"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />

Found the solution, it was not related to the code or android. I'm using a Xiomi phone and on the internet it is advised to disable the MIUI Optimisation in the dev options when coding. It was the issue, re-enabling it and rebooting the phone solved the problem. Thanks for the answers !

Related

Button not responding XML issue?

I was working yesterday and not today. Have two buttons one to go back, one that is an emergency button that calls a method to open the dialer for a call to the ambulance.
I think it may be an XML problem not sure was working fine now unresponsive maybe I changed something I shouldn't have. When it was clicking earlier it was saying the method could not be found which I just don't get it as it is in the correct file
ReportActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//allows for a smoother transition
overridePendingTransition(0, 0);
setContentView(R.layout.activity_report);
EditText incidentReport = this.findViewById(R.id.Incident_Report);
incidentReport.setSelection(0);
try {
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ReportActivity.this, MainActivity.class);
startActivity(intent);
}
});
} catch (NullPointerException n) {
Toast.makeText(this, "Error,", Toast.LENGTH_LONG);
}
try {
emergency.setOnClickListener(new View.OnClickListener() {
public void onClick(#NonNull View v) {
Intent call = new Intent(ReportActivity.this, CallActivity.class);
startActivity(call);
}
});
} catch (NullPointerException n) {
Toast.makeText(this, "Error,", Toast.LENGTH_LONG);
}
}
#Override
public void onClick(View v) {
}
private boolean checkPermission(String permission) {
int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
return (permissionCheck == PackageManager.PERMISSION_GRANTED);
}
public void call(View view) {
if (checkPermission("android.permission.CALL_PHONE")) {
Intent call = new Intent(Intent.ACTION_DIAL);
String number = "tel:" + getString(R.string.phone_number);
call.setData(Uri.parse(number));
startActivity(call);
}
}
}
activity_report.xml
android:gravity="start"
android:hint="#string/Hint"
android:inputType="text"
android:textAlignment="textStart"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintBottom_toTopOf="#+id/submit_btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/submit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="80dp"
android:layout_marginLeft="80dp"
android:layout_marginTop="32dp"
android:background="#drawable/yes_button"
android:text="Submit"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Incident_Report" />
<Button
android:id="#+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="80dp"
android:layout_marginRight="80dp"
android:background="#drawable/diagnose_button"
android:onClick="onClick"
android:text="Back"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Incident_Report" />
<Button
android:id="#+id/emergency_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="131dp"
android:layout_marginBottom="106dp"
android:background="#drawable/no_button"
android:onClick="call"
android:text="EMERGENCY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/submit_btn" />
</androidx.constraintlayout.widget.ConstraintLayout>
If you plan on using android:onClick="call"in your xml then you should also have a corresponding function called callin your activity and the logic to perform the click goes inside it.
If you plan on extending the View.onClickListener then inside your override void onClick() you can have a switch statement of your button ids and perform your logic
alternatively you can ignore the first two and get the id of the button and implement the click logic inside the onCreate()

Webview get focus automatically when removing URL from Edit Text

I have one Edit Text, 5 buttons and a Webview. Webview load url when user type url in edit text and tap Go button or hit Enter on soft keyboard.
I have three problems here.
1-WebView loads website for example "www.google.com" but soft keyboard does not hide itself. I want to hide it like other browser do.
2-When user open a specific url and then try to remove it from Edit Text to open a different url, webview start loading that incomplete url and get focus automatically on every letter removing. For example user loads "www.google.com" then he try to remove url from end and as he remove "m", webview try to load "www.google.co" then edit text is out of focus and webview stole focus from it then user have to tap in edit text again to remove url but it tries to load after every letter removing. I need Webview to load url only when user tap on Go button or hit Enter on soft keyboard.
Update (forgot to add third problem, here it is)
3-Where can i check when WebView CanGoBack and CanGoForward because i want to set visibility of Back and Forward buttons to false at startup and enabled these two buttons while they CanGoBack and CanGoForward. Where should i put my piece of code to check these conditions?
I hope you guys can understand what i am trying to say. Sorry for my poor english.
Here is my xml code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="13"
tools:context="com.hbss.chatapp.rashidfaheem.hybridsoftwaresolutions.rashidfaheem.youseebrowser.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:weightSum="4"
>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/etUrl"
android:layout_weight="3"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="GO"
android:id="#+id/btnGo"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Back"
android:id="#+id/btnBack"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Forward"
android:id="#+id/btnForward"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear"
android:id="#+id/btnClear"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Reload"
android:id="#+id/btnReload"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="11"
>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/wb"
/>
</LinearLayout>
</LinearLayout>
Here is my java code.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText etUrl;
Button btnGo, btnBack, btnForward, btnClear, btnReload;
WebView wb;
String url;
View v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wb = (WebView) findViewById(R.id.wb);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setUseWideViewPort(true);
wb.getSettings().setLoadWithOverviewMode(true);
wb.setWebViewClient(new ourClient());
etUrl = (EditText) findViewById(R.id.etUrl);
btnGo = (Button) findViewById(R.id.btnGo);
btnBack = (Button) findViewById(R.id.btnBack);
btnForward = (Button) findViewById(R.id.btnForward);
btnClear = (Button) findViewById(R.id.btnClear);
btnReload = (Button) findViewById(R.id.btnReload);
btnGo.setOnClickListener(this);
btnReload.setOnClickListener(this);
btnBack.setOnClickListener(this);
btnForward.setOnClickListener(this);
btnClear.setOnClickListener(this);
etUrl.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (keyEvent.getAction()==KeyEvent.ACTION_DOWN && i==KeyEvent.KEYCODE_ENTER) {
return true;
}
load();
return false;
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnGo:
load();
break;
case R.id.btnBack:
if (wb.canGoBack())
wb.goBack();
break;
case R.id.btnForward:
if (wb.canGoForward())
wb.goForward();
break;
case R.id.btnReload:
wb.reload();
break;
case R.id.btnClear:
wb.clearHistory();
break;
}
}
public void load(){
url = etUrl.getText().toString();
if (!url.startsWith("http://")) {
url = "http://" + url;
}
try {
wb.loadUrl(url);
wb.requestFocus();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), " " + e, Toast.LENGTH_LONG).show();
}
}
}
use this method to hide the keyboard:
public static void hideSoftKeyboard(Activity context) {
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null)
inputManager.hideSoftInputFromWindow(context.getWindow()
.getDecorView().getApplicationWindowToken(), 0);
context.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
call it in your load() method like:
hideSoftKeyboard(MainActivity.this);
For your second question you need to call your method inside the condition like:
etUrl.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if ((keyEvent.getAction()==KeyEvent.ACTION_DOWN) && (i==KeyEvent.KEYCODE_ENTER)){
load(); //add it here
return true;
}
return false;
}
});
EDIT
For the webview go back feature: override onKeyDown in your activity and check condition like:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && wb.canGoBack()) {
wb.goBack();
//show your back button here
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
//show other buttons
return super.onKeyDown(keyCode, event);
}
You can add the check in your onResume() and load() also and show your button accordingly..
#Override
protected void onResume() {
super.onResume();
if(wb.canGoBack()){
//show back button}
else{
//other button
}
}

TextEdit validation overlays show password icon

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
}

Layout elements duplicated on Samsung Galaxy Tab 2

I've been developing a simple android application.
It worked fine on several virtual devices and on HTC One S, but when I started it on Samsung Galaxy Tab 2 with Android 4.0.4 all the elements on the layout was duplicated. Its visible with the virtual keyboard and without it.
Here is the Layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/password_label"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/password_view" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ok_label"
android:id="#+id/password_confirm"
android:layout_gravity="center_horizontal"
android:onClick="checkPassword" />
</LinearLayout>
And the Activity source code:
public class PasswordActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_password);
Button button = (Button) findViewById(R.id.password_confirm);
if (SharedPreferencesHandler.isPreferenceSet(this, SharedPreferencesHandler.PreferenceKey.PASSWORD_PREFERENCE_KEY)) {
button.setText(R.string.ok_label);
} else {
button.setText(R.string.save_label);
}
EditText editText = (EditText) findViewById(R.id.password_view);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
checkPassword();
handled = true;
}
return handled;
}
});
}
//some utility methods
}
Here is a screenshot of that bug:

Keyboard not shown on inflated editText even after clicking on it

Background
I have a form-like activity, which has some views that can be created dynamically upon pressing.
I'm using an xml for each field that is inflated upon clicking on a button.
What I need is that upon choosing to add a new item, it will get focus, scroll if needed, and show the keyboard so that the user can type things into it. The keyboard may be shown upon adding the field or when clicking on the EditText.
The problem
For some reason, on some devices (and I don't think it's even an android version issue) when inflating the new view, the editText within it can get focus but it doesn't show the keyboard, even if it has focus and the user clicks on it.
In such a case, the only way to show the keyboard is to click on another EditText.
I've tested it, and noticed that it doesn't occur when I don't use xml at all, meaning when i create the views only in code.
The question
Why does it occur? What can I do in order to fix it?
I've already tried so many possible solutions, but none work on all devices.
Sample Code
the next code has the described issue on xperia j (android 4.0.4) an galaxy mini (android 2.3.6) .
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup container = (ViewGroup) findViewById(R.id.LinearLayout1);
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
final View view = inflater.inflate(R.layout.field, null);
// using the next code works when using it instead of inflating a layout:
// final EditText editText = new EditText(MainActivity.this);
// editText.setText("item " + container.getChildCount());
container.addView(view);
}
});
}
the field layout file:
<?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:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFffffff"
android:gravity="center_vertical" >
<Spinner
android:id="#+id/typeSpinner"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:background="#null"
android:padding="5dp" />
<include
android:id="#+id/removeItemView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
layout="#layout/remove_item_view" />
<EditText
android:id="#+id/fieldEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/removeItemView"
android:layout_toRightOf="#+id/typeSpinner"
android:ems="10"
android:focusable="true"
android:focusableInTouchMode="true"
android:hint="field"
android:imeOptions="actionDone"
android:inputType="phone"
android:minWidth="200dp"
android:padding="5dp"
android:singleLine="true"
tools:ignore="HardcodedText" >
<requestFocus />
</EditText>
</RelativeLayout>
the main layout file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
tools:ignore="HardcodedText" />
</LinearLayout>
</ScrollView>
EDIT: found a partial solution which won't show the keyboard right away, but at least it will be shown when pressing the editText:
public static void forceFocusOnView(final View view) {
if (view == null)
return;
view.post(new Runnable() {
#Override
public void run() {
view.clearFocus();
view.post(new Runnable() {
#Override
public void run() {
view.requestFocus();
}
});
}
});
}
I'm not sure in a reason of that problem. Could be some missmatches when Android sdk were rewritten in order to match some devices.
So I think that the best solution to you is to show your keyboard manually and do not try to move a train, just take the path of the least resistance:
EditText et=(EditText)this.findViewById(R.id.edit_text);
et.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et, 0);<----------------
}
});
Here you go , man. Wish you luck.
Oh i see...
private EditText et;
private Runnable setFocus;
......
protected void onCreate(...){
.
.
.
setFocus=new Runnable(){
#Override
public void run() {
et.requestFocus();
}
};
}
....
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
final View view = inflater.inflate(R.layout.field, null);
//try this:
et=(EditText)view.findViewById(r.id.fieldEditText);
et.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et, 0);<----------------
}
});
container.addView(view);
container.requestLayout();<--------------
et.postDelayed(setFocus,300);
}
});

Categories

Resources